unit SMSQSAR;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, StrUtils, ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Edit1: TEdit;
    Button3: TButton;
    Label1: TLabel;
    Edit2: TEdit;
    Button4: TButton;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    Button5: TButton;
    Edit3: TEdit;
    Label8: TLabel;
    Button6: TButton;
    Edit4: TEdit;
    Edit5: TEdit;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    Edit6: TEdit;
    Edit7: TEdit;
    Edit9: TEdit;
    Label14: TLabel;
    RadioButton1: TRadioButton;
    RadioButton2: TRadioButton;
    Button7: TButton;
    Label15: TLabel;
    Edit10: TEdit;
    Edit11: TEdit;
    Label18: TLabel;
    Edit14: TEdit;
    Edit15: TEdit;
    Edit16: TEdit;
    Edit17: TEdit;
    Button8: TButton;
    Edit18: TEdit;
    Button9: TButton;
    Button14: TButton;
    Edit20: TEdit;
    Label22: TLabel;
    Edit21: TEdit;
    Label23: TLabel;
    CheckBox1: TCheckBox;
    CheckBox2: TCheckBox;
    CheckBox3: TCheckBox;
    CheckBox4: TCheckBox;
    CheckBox5: TCheckBox;
    CheckBox6: TCheckBox;
    Label24: TLabel;
    Edit22: TEdit;
    Edit23: TEdit;
    Edit24: TEdit;
    Label25: TLabel;
    Label26: TLabel;
    Button13: TButton;
    CheckBox7: TCheckBox;
    CheckBox8: TCheckBox;
    CheckBox9: TCheckBox;
    CheckBox10: TCheckBox;
    CheckBox11: TCheckBox;
    Button16: TButton;
    Button17: TButton;
    Edit19: TEdit;
    CheckBox12: TCheckBox;
    CheckBox13: TCheckBox;
    Edit25: TEdit;
    Button19: TButton;
    Label21: TLabel;
    Edit26: TEdit;
    Edit27: TEdit;
    Label27: TLabel;
    Edit28: TEdit;
    Edit29: TEdit;
    Label28: TLabel;
    Edit30: TEdit;
    Edit31: TEdit;
    Label29: TLabel;
    CheckBox14: TCheckBox;
    CheckBox15: TCheckBox;
    CheckBox16: TCheckBox;
    CheckBox17: TCheckBox;
    CheckBox18: TCheckBox;
    CheckBox19: TCheckBox;
    CheckBox20: TCheckBox;
    CheckBox21: TCheckBox;
    CheckBox22: TCheckBox;
    CheckBox23: TCheckBox;
    Label5: TLabel;
    Label13: TLabel;
    Label16: TLabel;
    Label17: TLabel;
    Label19: TLabel;
    Button15: TButton;
    Button18: TButton;
    Label20: TLabel;
    CheckBox24: TCheckBox;
    Edit8: TEdit;
    Edit12: TEdit;
    Edit13: TEdit;
    Label30: TLabel;
    Edit32: TEdit;
    Edit33: TEdit;
    Edit34: TEdit;
    Edit35: TEdit;
    Label31: TLabel;
    Edit36: TEdit;
    Label32: TLabel;
    Button20: TButton;
    Button21: TButton;
    Button22: TButton;
    CheckBox25: TCheckBox;
    Button23: TButton;
    Button24: TButton;
    Edit37: TEdit;
    Label33: TLabel;
    Edit38: TEdit;
    Edit39: TEdit;
    Label34: TLabel;
    Label35: TLabel;
    Button25: TButton;
    Button26: TButton;
    Edit40: TEdit;
    Edit41: TEdit;
    Label36: TLabel;
    Edit42: TEdit;
    Label37: TLabel;
    Edit43: TEdit;
    Button10: TButton;
    Button11: TButton;
    Edit44: TEdit;
    Label38: TLabel;
    Button12: TButton;
    Edit45: TEdit;
    Edit46: TEdit;
    Label39: TLabel;
    Label40: TLabel;
    Edit47: TEdit;
    Label41: TLabel;
    Label42: TLabel;
    Button27: TButton;
    Edit48: TEdit;
    Edit49: TEdit;
    Button28: TButton;
    Edit50: TEdit;
    Button29: TButton;
    Label43: TLabel;
    Label44: TLabel;
    Label45: TLabel;
    CheckBox26: TCheckBox;
    CheckBox27: TCheckBox;
    CheckBox28: TCheckBox;
    CheckBox29: TCheckBox;
    CheckBox30: TCheckBox;
    CheckBox31: TCheckBox;
    CheckBox32: TCheckBox;
    Label46: TLabel;
    Label47: TLabel;
    Label48: TLabel;
    Label49: TLabel;
    Button30: TButton;
    Button31: TButton;
    Button32: TButton;
    Label50: TLabel;
    CheckBox33: TCheckBox;
    CheckBox34: TCheckBox;
    Label51: TLabel;
    Label52: TLabel;
    CheckBox35: TCheckBox;
    Label53: TLabel;
    Label54: TLabel;
    Label55: TLabel;
    Label56: TLabel;
    Label57: TLabel;
    Label58: TLabel;
    Button33: TButton;
    CheckBox36: TCheckBox;
    CheckBox37: TCheckBox;
    CheckBox38: TCheckBox;
    CheckBox39: TCheckBox;
    CheckBox40: TCheckBox;
    CheckBox41: TCheckBox;
    CheckBox42: TCheckBox;
    CheckBox43: TCheckBox;
    CheckBox45: TCheckBox;
    CheckBox46: TCheckBox;
    CheckBox47: TCheckBox;
    CheckBox48: TCheckBox;
    CheckBox49: TCheckBox;
    CheckBox50: TCheckBox;
    CheckBox51: TCheckBox;
    CheckBox52: TCheckBox;
    CheckBox53: TCheckBox;
    CheckBox54: TCheckBox;
    CheckBox55: TCheckBox;
    CheckBox56: TCheckBox;
    CheckBox58: TCheckBox;
    CheckBox60: TCheckBox;
    CheckBox61: TCheckBox;
    CheckBox62: TCheckBox;
    CheckBox63: TCheckBox;
    CheckBox64: TCheckBox;
    CheckBox65: TCheckBox;
    CheckBox66: TCheckBox;
    CheckBox67: TCheckBox;
    CheckBox68: TCheckBox;
    CheckBox69: TCheckBox;
    CheckBox70: TCheckBox;
    CheckBox71: TCheckBox;
    CheckBox72: TCheckBox;
    CheckBox73: TCheckBox;
    CheckBox74: TCheckBox;
    CheckBox76: TCheckBox;
    CheckBox77: TCheckBox;
    CheckBox78: TCheckBox;
    CheckBox79: TCheckBox;
    CheckBox80: TCheckBox;
    CheckBox81: TCheckBox;
    CheckBox82: TCheckBox;
    CheckBox84: TCheckBox;
    CheckBox85: TCheckBox;
    CheckBox86: TCheckBox;
    CheckBox87: TCheckBox;
    CheckBox88: TCheckBox;
    CheckBox89: TCheckBox;
    CheckBox91: TCheckBox;
    CheckBox92: TCheckBox;
    CheckBox93: TCheckBox;
    CheckBox94: TCheckBox;
    CheckBox95: TCheckBox;
    CheckBox96: TCheckBox;
    CheckBox97: TCheckBox;
    CheckBox99: TCheckBox;
    CheckBox100: TCheckBox;
    CheckBox101: TCheckBox;
    CheckBox102: TCheckBox;
    CheckBox103: TCheckBox;
    CheckBox104: TCheckBox;
    CheckBox105: TCheckBox;
    CheckBox106: TCheckBox;
    CheckBox107: TCheckBox;
    CheckBox108: TCheckBox;
    CheckBox109: TCheckBox;
    CheckBox110: TCheckBox;
    CheckBox112: TCheckBox;
    CheckBox113: TCheckBox;
    CheckBox114: TCheckBox;
    CheckBox115: TCheckBox;
    CheckBox116: TCheckBox;
    CheckBox117: TCheckBox;
    CheckBox118: TCheckBox;
    CheckBox119: TCheckBox;
    CheckBox120: TCheckBox;
    CheckBox121: TCheckBox;
    CheckBox122: TCheckBox;
    CheckBox123: TCheckBox;
    CheckBox124: TCheckBox;
    CheckBox125: TCheckBox;
    CheckBox127: TCheckBox;
    CheckBox128: TCheckBox;
    CheckBox129: TCheckBox;
    CheckBox130: TCheckBox;
    CheckBox131: TCheckBox;
    CheckBox133: TCheckBox;
    CheckBox134: TCheckBox;
    CheckBox135: TCheckBox;
    CheckBox136: TCheckBox;
    CheckBox137: TCheckBox;
    Label59: TLabel;
    Label60: TLabel;
    Label61: TLabel;
    Label62: TLabel;
    Label63: TLabel;
    Label64: TLabel;
    Label65: TLabel;
    Label66: TLabel;
    Label67: TLabel;
    Label68: TLabel;
    Label69: TLabel;
    Label70: TLabel;
    Label71: TLabel;
    Label72: TLabel;
    Label73: TLabel;
    Label74: TLabel;
    Label75: TLabel;
    Label76: TLabel;
    Label77: TLabel;
    Label78: TLabel;
    CheckBox44: TCheckBox;
    CheckBox57: TCheckBox;
    CheckBox59: TCheckBox;
    CheckBox75: TCheckBox;
    CheckBox83: TCheckBox;
    CheckBox90: TCheckBox;
    CheckBox98: TCheckBox;
    CheckBox111: TCheckBox;
    CheckBox126: TCheckBox;
    CheckBox132: TCheckBox;
    Label79: TLabel;
    Label80: TLabel;
    Label81: TLabel;
    Label82: TLabel;
    Label83: TLabel;
    Label84: TLabel;
    Label85: TLabel;
    Label86: TLabel;
    Label87: TLabel;
    Label88: TLabel;
    Button34: TButton;
    Button35: TButton;
    Button36: TButton;
    Button37: TButton;
    Button38: TButton;
    Button39: TButton;
    Button40: TButton;
    Button41: TButton;
    Button42: TButton;
    Button43: TButton;
    Button44: TButton;
    Button45: TButton;
    Button46: TButton;
    Button47: TButton;
    Button48: TButton;
    Button49: TButton;
    Button50: TButton;
    Button51: TButton;
    Button52: TButton;
    Button53: TButton;
    Button54: TButton;
    Button55: TButton;
    Button56: TButton;
    Button57: TButton;
    Button58: TButton;
    Button59: TButton;
    Button60: TButton;
    Button61: TButton;
    Button62: TButton;
    Button63: TButton;
    Button64: TButton;
    Button65: TButton;
    Button66: TButton;
    Button67: TButton;
    Button68: TButton;
    Button69: TButton;
    Label89: TLabel;
    Edit51: TEdit;
    Edit52: TEdit;
    Button70: TButton;
    Button71: TButton;
    Button72: TButton;
    chk1: TCheckBox;
    Label90: TLabel;
    Edit53: TEdit;
    Label91: TLabel;
    Button73: TButton;
    Button74: TButton;
    Button75: TButton;
    Edit54: TEdit;

    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure Button5Click(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure RadioButton1Click(Sender: TObject);
    procedure RadioButton2Click(Sender: TObject);
    procedure RadioButton3Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button7Click(Sender: TObject);
    procedure Button9Click(Sender: TObject);
    procedure RadioButton4Click(Sender: TObject);
    procedure Button10Click(Sender: TObject);
    procedure Button13Click(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure Button8Click(Sender: TObject);
    procedure Button14Click(Sender: TObject);
    procedure Button16Click(Sender: TObject);
    procedure Button17Click(Sender: TObject);
    procedure Button19Click(Sender: TObject);
    procedure Button20Click(Sender: TObject);
    procedure Button15Click(Sender: TObject);
    procedure Button18Click(Sender: TObject);
    procedure Button21Click(Sender: TObject);
    procedure Button23Click(Sender: TObject);
    procedure Button11Click(Sender: TObject);
    procedure Button12Click(Sender: TObject);
    procedure Button27Click(Sender: TObject);
    procedure Button28Click(Sender: TObject);
    procedure Button29Click(Sender: TObject);
    procedure Button30Click(Sender: TObject);
    procedure Button31Click(Sender: TObject);
    procedure Button32Click(Sender: TObject);
    procedure Button24Click(Sender: TObject);
    procedure Button33Click(Sender: TObject);
    procedure Button34Click(Sender: TObject);
    procedure Button35Click(Sender: TObject);
    procedure Button36Click(Sender: TObject);
    procedure Button37Click(Sender: TObject);
    procedure Button38Click(Sender: TObject);
    procedure Button39Click(Sender: TObject);
    procedure Button40Click(Sender: TObject);
    procedure Button41Click(Sender: TObject);
    procedure Button42Click(Sender: TObject);
    procedure Button43Click(Sender: TObject);
    procedure Button44Click(Sender: TObject);
    procedure Button45Click(Sender: TObject);
    procedure Button46Click(Sender: TObject);
    procedure Button47Click(Sender: TObject);
    procedure Button48Click(Sender: TObject);
    procedure Button49Click(Sender: TObject);
    procedure Button55Click(Sender: TObject);
    procedure Button56Click(Sender: TObject);
    procedure Button57Click(Sender: TObject);
    procedure Button58Click(Sender: TObject);
    procedure Button59Click(Sender: TObject);
    procedure Button50Click(Sender: TObject);
    procedure Button60Click(Sender: TObject);
    procedure Button61Click(Sender: TObject);
    procedure Button62Click(Sender: TObject);
    procedure Button63Click(Sender: TObject);
    procedure Button51Click(Sender: TObject);
    procedure Button64Click(Sender: TObject);
    procedure Button65Click(Sender: TObject);
    procedure Button66Click(Sender: TObject);
    procedure Button52Click(Sender: TObject);
    procedure Button67Click(Sender: TObject);
    procedure Button68Click(Sender: TObject);
    procedure Button53Click(Sender: TObject);
    procedure Button69Click(Sender: TObject);
    procedure Button54Click(Sender: TObject);
    procedure Button70Click(Sender: TObject);
    procedure Button71Click(Sender: TObject);
    procedure Button72Click(Sender: TObject);
    procedure Button73Click(Sender: TObject);
    procedure Button74Click(Sender: TObject);
    procedure Button75Click(Sender: TObject);
//    procedure Button27Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2, Unit3;

{$R *.dfm}

const

DuplicatesFileName='#Duplicates.txt';
mantissaPA = 3; // number of digits after decimal dot for PA (endpoint)
MaxSize = 700; // Sergej data February 17, 2011 size of molecular graph

GIN       ='x';          // indicator of global SMILES invariants
BCE       ='~';          // indicator of the End of SMILES
BAR       ='.';          // free place in the SAk blank
reBAR     =chr(149);
//off       =0.0;          // passivator for SFk
//sd        =0.001;      // optimiz parameter first
//ssd       =0.001;      // optimiz parameter second

MaxSMILESLength=1000;     // for Fullerenes calculations
MinimumStructurForTestSet = 10;    // Idealization, outliers removing

MaxSMS    = 30000;       // maximum of SMILES strings
MaxSF     = 7000;        // maximum of SMILES fragments
MaxCharSF =  12;         // number of symbols in SF representation
//Nit       = 100;       // number of Monte Carlo iterations

minx=0.0;maxx=1.0;       // Interval values along  abscissa X-line
miny=0.0;maxy=1.0;       // Interval values along  ordinate axes Y-line

BasisOfStart=0.01;       // For calculation of the Start Values of CW(SFk)
ffD=4;                   // number digits after decimal point x.xxxxxxx
ffP=4;                   // expr calc expr-calc x.xxx
// Nscrambling=300;         // number shuffting in Y-scrambling test
MaxProbes=30;               // number of probes in (T,N) search or
                            // in Las Vegas searching
// MaxEpochs = 100;
MaxAtomNumber =104;
MaxAO =20;
MaxThreshold = 30;
MaxInput   = 59000; // type paira expr[] calc[] in output.txt file
//Solomon = 3.0; // degree to normaliz defect of split as function of T and Nact
//Screen ='Screen.txt'; // file contain position of screen

Report = '!Symmetry.txt'; // February13,2023 description of symmetry and chaos
//MaxLV = 10; // the number of attempts to improve split via Las Vegas May28,2024

type
    str4        = string[4];
    CWsName     = string[MaxCharSF];
    SFlist      = array[1..MaxSF  ] of CWsName; // lists of SFk
    DCWPA       = array[1..MaxSMS ] of real;
    Probability = array[1..maxSF  ] of real;
    Presence    = array[0..MaxSF  ] of integer;

    Adjacency = Array[1..MaxSize, 1..MaxSize] of Integer; // Sergej data Feb 17, 2011
    atomic_name=string;

    ChemicalElements = Array[1..MaxSize] of Atomic_name;
    vector      = array[1..maxsize] of CWsName;
    TRNCLBTST = array[1..MaxSMS] of char; // + - #

var
// May 26, 2014
x10, y10,
x20, y20,
x30, y30,
x40, y40,
rx , Ry :integer;

do_vld:boolean; // do or do not calculation for the validtaion set

     mnx,mxx,
     mny,mxy:real;

(*
x10 =57 ; y10 =120;      // Point of origin Plot for the Training Ser
x20 =57 ; y20 =290;      // Point of origin plot for the Test Set
x30 =57 ; y30 =450;      // Point of origin plot for the External Test Set
Rx  =157 ; Ry  =100;     // Size of the quadratic plots
*)


                           // March 29, 2011
    vertex, degree:vector; // for calculation of local graph invariants
                           // and for registration of atom names

AO:array[1..MaxAtomNumber,1..MaxAO] of str4;// load of Atomic orbitals such as 1s2, 2s2,... 3d10
Nao:array[1..MaxAtomNumber] of integer;   // number of aos for a given chemical element

N_HFG, N_HSG, N_GAO:integer; // size of HFG HSG, and GAO

    ListOfAO,
    ListOfAtom:ChemicalElements;

    RecommFileName:string;             // Name for file with T* and N*
    Chana,
    cas,
    casLV,                             // CAS numbers
    sms:array[1..MaxSMS] of string;    // array of SMILES
    types2,
    types:TRNCLBTST;                   // type of set (+/-/#)

    HyperCode,                         // 0 ec0, 1 ec1, 2 ec2, ..., 8 nnc
                                       // code for hyper index (Nov 4, 2015)
    nsms:integer;                      // Number of SMILES strings
    HI_SF_list,                        // List of SF for Hyper Index (HI)
                                       // calculation Nov 4, 2015
    Global_SF_list,                    // Lists of SF on set of SMILES
    Local_SF_list: SFlist;             // List of SFk for single SMILES

    N_loc,           // number of SF in single SMILES
    N_Glb:integer;   // number of SF in training set

    CWdefect: array[0..MaxSF] of real;

    CW  :array[0..MaxProbes,0..MaxSF] of real;
    CWactive: array[1..MaxSF] of boolean;

    Rm2:real;        // Roy characteristics of predictability
    KroyN:integer;   // number of structures in TST
    KRoyX,KRoyY,     // calculation of Rm2 etc.
    dcw2,            // April 13, 2011
    PA_Y_scrambling,
    PAcalc,
    PA01,
    pa2,             // Idealization = deoutlaering, i.e.:
                     // worst1, Rtest better, worst2, Rtest better, ... etc.
    pa,              // PA - Property / Activity
    DefectSMILES,    // April 24, 2014: CORAL DA definition
    DCW :DCWPA;      // Descriptor of Correlation Weights

    nuc :array[1..MaxSMS,0..MaxSF] of integer; // Matrix numbers of SFk
                                               // for fast optimization
    ro  :array[1..MaxSF] of integer;           // random order of the SFk

                  // trns[0]=number of SMILES in training
                  // Tclb[0]=number of SMILES in calibration
                  // Tsts[0]=number of SMILES in test
    Trns,         // how much SMILESs of Training set contain the SFk
    Clbs,         // how much SMILESs of Calibration set conatin the SFk
    tsts,         // how much SMILESs of Test set contain the SFk
    Trn,          // how much SFk in all SFk of Training set
    Clb,          // how much SFk in all SFk of Calibration set
    Tst           // How much SFk in all SFk of Test set

    :presence;

    ptrn0,        // probability SAk in TRN,CLB,TST if limN=0
    pclb0,
    ptst0,

    Ptrn,         // probability SAk in TRN,CLB,TST for given LimN<>0
    Pclb,
    Ptst

    :probability;


    IniCWs: boolean; // for installation CWs at start, and blocking
                     // instalation if some iterations have been done
    sd,              // optimization parameters
    ssd,
    alpha:real;      // R(work)=Rtrain+Rcalibr - abs(dR)*alpha
    Nit:integer;     // number of Monte Carlo iterations
    GraphParol,      // for show CAS
    Reject,
    Train,            // + training set
    Calib,            // - calibration set
    valid,            // * external validation
    Test  :char;      // # test set
    Style :char;      // 1 TC-T, 2 T-CT, 3 T-T
    DoLIne:boolean;   // draw or not line in plot expr & calc
    CASdelta,         // dk in the showCAS dk=+1 or -1
    LimNI : integer;  // Lim number SFk in Training set i.e., 1,2,3...
    DoNotQ2:boolean;  // Bloking calculation Q2 during optimization
    stopping:boolean; // Interruption of the optimiz;
    PAmodify:boolean; // x->log(1/x) or x->x
    level1,           // s
    level2,           // ss
    level3:boolean;   // sss
    series:char;      // yes (y) means doing of limNI=x to y and probe=x' to y'
    SMILESAk:char;    // Choice of limS (yes) or LimN (no)
//    fd,fp:integer;    // format for DCW:12:fd PA:12:FP
    scheme:char;      // * multiplicative scheme + additive scheme
    //off:real;         // * off=1; + off=0; passivator for SAk
    authomat,         // selection of automatic or interactvie mode
    Save_all_CWs:boolean; // save all (Save_all_CWs=True) or only active CWs
    nChana:integer;
    Threshold:real; // definition of Toxic / non Toxic compounds by pa-values
    bestR:real;     // control for best model=F(bestlim,bestr);
    bestlim:integer;// selection of maximal R for test set
    dKweight,
    dRweight,
    dCweight:real;  // in NewCorrelation Balance 2R-dR*0.1-dC*dCweight
    probe:integer;  // number of probes 1-3-5...
    dir:string; // search OR model directories

    onlyFirst,  // only s1 without s2, s3, etc. // October 14, 2016

    comma:boolean; // decimal dot or decimal comma?

    MaxSMILESLength2:integer;    // Max symbols for SMILES printing

    best_it_TRN_r,
    best_it_TRN_s,
    Best_it_TST_r,
    Best_it_TST_s
                   :integer;     // output of the best results over
    best_r2_TRN,
    best_s_TRN,
    best_r2_TST,
    best_s_TST:real;            // all co-correlations, Nepoch

    Total_best_TRN_r,
    Total_best_TRN_s,
    Total_best_TST_r,
    total_best_TST_s
                     :real;      //
    total_best_probe_TRN_r,
    total_best_probe_TRN_s,
    total_best_probe_TST_r,
    total_best_probe_TST_s,

    total_best_nepoch_TRN_r,
    total_best_nepoch_TRN_s,
    total_best_nepoch_TST_r,
    total_best_nepoch_TST_s,

    total_best_threshold_TRN_r,
    total_best_threshold_TRN_s,
    total_best_threshold_TST_r,
    total_best_threshold_TST_s

    :integer;

    TP,TN,FP,FN:integer; // for classification model interface


    off:real;
    DotInSMILES:string;
    userinformed:boolean; // about impossibility to use graphs

    R2_TRN_BEST,
    S_TRN_BEST,
    R2_TST_BEST,
    S_TST_BEST,
    NEPOCH_BEST_TRN_r,
    NEPOCH_BEST_TRN_s,
    NEPOCH_BEST_TST_r,
    NEPOCH_BEST_TST_s
    : array[0..MaxProbes,0..MaxThreshold] of real;

//  December 6, 2011 addition classification model
    classification:boolean;
    min01,max01,middle01:real;
    GTP,GTN,GFP,GFN:integer;
    Display_memory:string;
    AveDefectSMILES:real;
    RVLD:real;

    tps,tns,fps,fns:string;

    Show_TPTNFPFN:boolean; // digital representation of classification
                           // on diagram "expr-calc"

    Adj2,
    Adj:adjacency;


//  MaxInput=1000(?); array for print in file Output pair expr[] calc[]
//  this file is input-file for kb.exe in VLD-statistics, where
//  R2, Q2, k,k', Rm2, etc are calculated
//  December 19, 2013
    exprcalc:array[1..MaxInput,1..2] of real;
    SplitDefect:array[1..MaxThreshold]of real;
    // summ of P(SAk) in TRN - P(SAk) in TST for SAk which are not blocked

    dotsize,           // size of dots in XY-plots March15,2024
    switch012:integer; // selection clusters +- or oppositionis/supporters
                       // March14,2024
    RedGreen,     // color dots in plot Expr vs Calc May11,2023
    show_optimiz, // May4,2023 show process of optimization or not
    Print_VLD,
    Model_is_loaded:boolean;

    density:real;       // May5,2023
    NactiveCWs,         // density = NactiveCWs / Nall (i.e. N_glb)
    CCCP_style,         // June11,2024
    IIC_Style,          // November 4, 2019
    CCI_Style: integer; // 0 = only CLB; 1 = only iTRN; 2 = iTRN together CLB

    FYI:text; // history of improvement for split December 16, 2019
    modeldoc:string; // save model details for each k-th probe  December 16, 2019
    SAS:boolean; // Stop and Save [model details]
    workperc:string; // W% for print in e1-k.txt November 14, 2019
    LV,LVbest:integer; // counter of probes in Las Vegas algorithm May27,2024
    LVRCmax:real;
    LVlist: array[1..MaxProbes] of string; // list of files with gradually improved #TotalSet.txt May28,2024

    APP:array [1..8,1..8] of integer;

    sym,         // checking up xyx interpretations
    domaino,     // December 1, 2022 file for outliers
    domain:text; // Oct7,2022 extraction of domain of applicability
    tester3,        // cheking up xyx
    tester4,        // cheking up symmetry fragments xyyx
    tester5,        // October19,2022 cheking up symmetry fragments xyzyx
    tester6,        // February3,2023 checking up chaos
    zzz             // for output symmetry and haos
    :string;
    marker:integer; // marker=0 write... marker=1 do not write...
    CCCP:real; // conformism coefficient of a correlation prediction January9,2024

    Bestprobe:integer; // the number of best probe in FYI April3,2024
    R2Cmax, // check up who is best in FYI
    R2A,
    R2P,
    R2C,
    R2V : real;
    version:integer; // 3 = CORAL3 Monte Carlo 5 = Las Vegas April3,2024
    percentexchanges:real; // how much shifting April5,2024
    APCV:boolean; // if APCV then validation involves to exchange objects else only APC not V April8,2024
    phase:integer; // pahse = 1 then do not if it=nit; phase <> 1 do May23,2024 

///////////////////////////////  SERGEJ Program February 17, 2011 (begin)

//const MaxSize = 100;
//type Adjacency = Array[1..MaxSize, 1..MaxSize] of Integer;

//procedure SMILES_in_Adj(SMILES:String; var Adj:Adjacency; var n:Integer);

//implementation
(**
procedure setscreen;
var x,y:integer;
    f:text;
begin
assign(f,'Screen.txt');
{$I-}
reset(f);
{$I+}
if IOResult <> 0 then exit;

readln(f,x);
readln(f,y);
//showmessage(IntTostr(x)+' '+IntTostr(y));
form1.Left:=x;
form1.Top:=y;
close(f);
end; // set screen

procedure savescreen;
var x,y:integer;
    f:text;
begin
x:=form1.Left;
y:=form1.Top;

assign(f,'Screen.txt'); rewrite(f);
writeln(f,x);
writeln(f,y);
//showmessage(IntTostr(x)+' '+IntTostr(y));
form1.Left:=x;
form1.Top:=y;
close(f);
end; // set screen
(**)

procedure halting(txt:string);
begin
showmessage(txt+#13+'Program will be halted');
halt;
end; // halting


type BondOrder = (BOND_SINGLE, BOND_DOUBLE, BOND_TRIPLE);

var rings: Array[1..1000] of Integer;
var atomId: Integer;

procedure init();
var i: Integer;
begin
  atomId := 0;
  for i := 0 to 1000 do
    rings[i] := 0;

end;
function getSymbolForOrganicSubsetElement(str: String; pos: Integer) : String;
var
  s: String;
  c: Char;
  count: Integer;
begin
  count := 0;                                 // gg
  s := MidStr(str, pos, 2);
  if AnsiMatchStr(s,
  ['Li','Be','Na','Mg','Al','Si','Cl','Ca',
//   'Sc',       sulphur and carbon
   'Ti','Cr','Mn','Fe',
//   'Co', carbon and oxygen
   'Ni',
   'Cu',
   'Zn','Ga','Ge','As','Se','Br','Rb','Sr','Zr','Nb','Mo','Tc','Ru','Rh',
   'Pd','Ag','Cd','In',
//   'Sn',  sulphur and nitrogen
   'Sb','Te',
//   'Cs',      carbon and sulphur
   'Ba','Lu','Hf','Ta','Re',
//   'Os',   oxygen and sulphur
   'Ir',
   'Pt','Au','Hg','Tl','Pb','Bi','Po','At','Fr','Ra','Lr','Rf','Db','Sg','Bh',
   'Hs'
  ]
  )
    then
    count := 2
  else
  begin
    c := str[pos];
    if StrScan('BCcNnOoFPSsI', c) <> nil then
      count := 1;
  end;

  if count > 0 then Result := MidStr(str, pos, count);
end;

function getAtomString(str: String; pos: Integer): String;
var
  i: Integer;
begin
  i := pos + 1;
  while str[i] <> ']' do
  begin
    Result := Result + str[i];
    i := i + 1;
  end;
end;

function getNumber(Str: String; pos: Integer): Integer;
var
  c: Char;
  s: String;
  i: Integer;
  r: Boolean;
  numbers: String;
begin
  numbers := '0123456789';
  r := true;
  i := pos;
  while r and (i <= Length(Str)) do
  begin
    c := Str[i];

    if StrScan(Addr(numbers[1]), c) <> nil then s := s + c
    else r := false;

    i := i + 1;
  end;
  Result := StrToInt(s);
end;

function assembleAtom(str: String): Integer;
begin
//TODO
  Result := 0;
end;

function OrderToInteger(order: BondOrder): Integer;
begin
  Result := -1;
  case order of
    BOND_SINGLE:
      Result := 1;

    BOND_DOUBLE:
      Result := 2;

    BOND_TRIPLE:
      Result := 3;
  end;
end;

procedure newBond(var adj: Adjacency; atomIndex1: Integer; atomIndex2: Integer; order: BondOrder);
begin
  adj[atomIndex1, atomIndex2] := OrderToInteger(order);
  adj[atomIndex2, atomIndex1] := OrderToInteger(order);
end;

procedure handleRing(var adj: Adjacency; atomIndex: Integer; ring: Integer; order: BondOrder);
var
  partner: Integer;
begin
  partner := rings[ring];
  if partner <> 0 then
    begin
      newBond(adj, atomIndex, partner, order);
      rings[ring] := 0;
    end
  else
    begin
      rings[ring] := atomIndex;
    end;
end;

function newAtomIndex(name: String):Integer;
begin
  if atomId < MaxSize then
  begin
    atomId := atomId + 1;
    Result := atomId;
  end
  else
    Result := 0;
end;

procedure parse(smiles: String; var adj: Adjacency; var ListOfAtom:ChemicalElements);
var
  _position: Integer;
  _myChar: Char;
  _symbol: String;
  _step: Integer;
  _result: Integer;
  _atom: Integer;
  _lastElement: Integer;
  _bondExists: Boolean;
  _bondOrder: BondOrder;

  _atomStack: Array of Integer;
  _sizeAtomStack: Integer;

  _orderStack: Array of BondOrder;
  _sizeOrderStack: Integer;
  //_isRing: Boolean;
  _number: Integer;
begin

  init();

  //_isRing := false;
  _bondExists := true;
  _lastElement := 0;
  _atom := 0;
  _sizeAtomStack := 0;
  _sizeOrderStack := 0;
  _bondOrder := BOND_SINGLE;
  _position := 1;
  _result := 0;
  while((_result = 0) and (_position <= Length(smiles))) do
  begin
    _myChar := smiles[_position];
    _step := 1;
    if (('Z' >= _myChar) and (_myChar >= 'A')) or ((_myChar >= 'a') and (_myChar <= 'z')) or (_myChar = '*') then
      begin
      if(_myChar = '*') then
        begin
        _atom := newAtomIndex(_myChar);
        _symbol := _myChar;
        end
      else
        begin
        _symbol := getSymbolForOrganicSubsetElement(smiles, _position);
        if _symbol = '' then
          begin
            _result := 1;
          end
        else
          begin
            _step := Length(_symbol);

            if (_step = 1) and (UpCase(_myChar) <> _myChar) then
              begin
                _atom := newAtomIndex(_myChar);
              end
            else
              _atom := newAtomIndex(_symbol);
          end //if symbol = '' then
        end; //if(myChar = '*')

        ListOfAtom[_atom] := _symbol;
//        molecule.addAtom(_atom);

        if(_lastElement <> 0) and _bondExists then
        begin
          newBond(adj, _atom, _lastElement, _bondOrder);
        end;
        _lastElement := _atom;
        _bondExists := true;
        _bondOrder := BOND_SINGLE;

      end //if (('Z' >= myChar)...
    else if (_myChar >= '0') and (_myChar <= '9') then
      begin
        //_isRing := true;
        _number := StrToInt(_myChar);
        handleRing(adj, _lastElement, _number, _bondOrder); //TODO _bondOrder is incorrect here
      end//if (myChar >= '0')...
    else
      begin
        case _myChar of
          '-':
          begin
          _bondOrder := BOND_SINGLE;
          end;//-

          '=':
          begin
          _bondOrder := BOND_DOUBLE;
          end; //=

          '#':
          begin
          _bondOrder := BOND_TRIPLE;
          end;//#

          '(':
          begin
          if _sizeAtomStack <= Length(_atomStack) then
            begin
              SetLength(_atomStack, _sizeAtomStack+1);
              _atomStack[_sizeAtomStack] := _lastElement;
            end;
          _sizeAtomStack := _sizeAtomStack + 1;

          if _sizeOrderStack <= Length(_orderStack) then
            begin
              SetLength(_orderStack, _sizeOrderStack+1);
              _orderStack[_sizeOrderStack] := _bondOrder;
            end;
          _sizeOrderStack := _sizeOrderStack + 1;
          end;//(

          ')':
          begin
            if(_sizeAtomStack = 0) or (_sizeOrderStack = 0) then _result := 2
            else
              begin
                _sizeAtomStack := _sizeAtomStack - 1;
                _sizeOrderStack := _sizeOrderStack - 1;
                _lastElement := _atomStack[_sizeAtomStack];
                _bondOrder := _orderStack[_sizeOrderStack];
                SetLength(_orderStack, _sizeOrderStack);
                SetLength(_atomStack, _sizeAtomStack);
              end;
          end;//)

          '.':
          begin
            _bondExists := false;
          end;//.

          '/':
          begin
            //ignore транс- или цис-
          end;

          '\':
          begin
            //ignore транс- или цис-
          end;

          '@':
          begin
            //ignore @ против часовой стрелки; @@ по часовой стрелке
            if (_position < Length(smiles) - 1) and (smiles[_position+1] = '@') then _step := 2
            else _step := 1;
          end;//@

          '[':
          begin
            _symbol := getAtomString(smiles, _position);
            _atom := assembleAtom(_symbol);
            //TODO
            _step := Length(_symbol)+2;
          end;

          '%':
          begin
            _number := getNumber(smiles, _position);
            handleRing(adj, _lastElement, _number, _bondOrder); //TODO _bondOrder is incorrect here
            _step := Length(IntToStr(_number))+1;
          end;

        end;
      end;

    _position := _position + _step;
  end;
end;

procedure SMILES_in_Adj(SMILES:String; var Adj:Adjacency; var n:Integer; var ListOfAtom:ChemicalElements);
var i, j: Integer;
    mem:boolean;
    memInt:integer;
begin

mem:=model_is_loaded;      // January 9, 2018
memInt:=app[8,8];

  n := 0;
  for i := 1 to MaxSize do
    for j := 1 to MaxSize do
      Adj[i,j] := 0;

  parse(SMILES, Adj, ListOfAtom);
  n := atomId;

model_is_loaded:=mem;
app[8,8]:=memInt;

end;

//end.

///////////////////////////////  SERGEJ Program February 17, 2011 (end)
// THE BEGIN of CORAL

procedure inc(var n:integer);
begin
n:=n+1;
end; // inc(integer)

(*
procedure Check_LimNI2(numberSF:integer);
var test:integer;
begin

if SMILESAk='S' then Test:=Trns [ numberSF ] // number SMILES with SAk in Trn
                else Test:=Trn  [ numberSF ];

if (Test<limNI) then CW[ probe,numberSF ]:=off;


end; // Check_LimNI
*)
Function Fischer_PA_C0_C1_DCW(var r:real;var n:integer):real;
var r2:real;
begin
r2:=sqr(r);
if (1-r2)>10e-22 then Fischer_PA_C0_C1_DCW:=(r2*(n-2))/(1-r2)
                 else Fischer_PA_c0_C1_DCW:=0.0;

end; // Fischer for Pa=C0+C1*DCW (i.e., one varaible model)

function fmtsee(see:real):integer;
var rez:integer;
begin
rez:=3;
if see<0.01 then rez:=5;
if see>1 then rez:=2;
if see>10 then rez:=1;
fmtsee:=rez;
end; // fmtsee

function StartValue:real;
begin
// StartValue:=1.0+ off*basisOfSTart +( 0.5 - random)*BasisOfStart;
StartValue:=( 0.5 - random);
end; // StartValue

procedure c0c1(parol:char; var x,y:DCWPA; var C0,C1,dc0,dc1:real);
label outof;
var kk,k,n,nset:integer;
    denominator,
    rcv0,
    c0b,c1b,c0x,c1x,
    sx,sx2,sy,sy2,sxy:real;
    order:array[1..maxsms] of integer;
    mean, sum1, sum2:real;
//    f:text;

procedure do_c0c1(var c0,c1,rcv0:real;nongrata:integer);
Label outof;
var k:integer;
    r1,
    a,b:real;
begin
sx:=0; sx2:=0; sy:=0; sy2:=0; sxy:=0;
n:=0;
for k:=1 to nset do
if k<>nongrata then
begin
inc(n);
sx:=sx+ x[order[k]];
sx2:=sx2+sqr(x[order[k]]);
sy:=sy+ y[order[k]];
sy2:=sy2+sqr(y[order[k]]);
sxy:=sxy+x[order[k]]*y[order[k]];
end; // k

if n<3 then
begin
ShowMessage
('A set contains 3 substances (or less): program should be halted');
//goto outof;
//halt;
end; // n<3

denominator:=n*sx2-sqr(sx);

if abs(denominator)<10e-22 then
begin
Form1.label48.Caption:='C0,C1: Denominator (n*Sx2-sqr(sx))<10e-22; scheme is '+scheme;
goto outof;
end; // denominator<10e-22

a:=(n*sxy-sx*sy);
r1:= (n*sx2-sx*sx)*(n*sy2-sy*sy);

if r1>0 then b:=sqrt( r1 ) else b:=1.0;

if abs(b)<10e-22 then
begin
showmessage('Error with calculation of C0 and C1. Probably system file is absent');
Halt;
end; // B<10e-22

rcv0:= a/b;

c0:=(sy*sx2-sx*sxy)/denominator;
c1:=(n*sxy-sx*sy)/denominator;
outof:
end; // do_c0c1

begin

kk:=0;
for k:=1 to nsms do
if types[k]=parol then begin inc(kk); order[kk]:=k; end;
nset:=kk;
if nset=0 then goto outof;

do_c0c1(c0b,c1b,rcv0,0);

//assign(f,'test');
//rewrite(f);
//writeln(f,'   ',c0b:9:3,c1b:9:3);
//writeln(f);

dc0:=0;
dc1:=0;
for k:=1 to nset do
begin
do_c0c1(c0x,c1x,rcv0,k);

dc0:=dc0+sqr(c0b-c0x);
dc1:=dc1+sqr(c1b-c1x);
//writeln(f,k:2,' ',c0x:9:3,c1x:9:3,c0b-c0x:9:3,dc0:9:3,c1b-c1x:9:3,dc1:9:3);
end;
c0:=c0b;
c1:=c1b;
if dc0>0 then dc0:=sqrt( dc0/(nset-1) );
if dc1>0 then dc1:=sqrt( dc1/(nset-1) );

//writeln(f,nset);
//writeln(f,dc0:9:3,dc1:9:3);
//close(f);
outof:
end; // c0c1

function See(parol:char; var c0,c1:real):real;
var k,n:integer;
    d,
    sum:real;
begin
sum:=0.0;
n:=0;
for k:=1 to nsms do
if types[k]=parol then
begin
d:=pa[k]-(c0+c1*dcw[k]);
sum:=sum+sqr(d);
inc(n);
end; // k
if n>3 then see:=sqrt(sum/(n-1))
       else see:=0.0;
end; // see

function SeeTotal(var c0,c1:real):real;
var k,n:integer;
    d,
    sum:real;
begin
sum:=0.0;
n:=0;
for k:=1 to nsms do
if (types[k]=Train) or (types[k]=Calib) or (types[k]=test) then
begin
d:=pa[k]-(c0+c1*dcw[k]);
sum:=sum+sqr(d);
inc(n);
end; // k
if n>3 then seetotal:=sqrt(sum/(n-1))
       else seetotal:=0.0;
end; // seetotal

function MAE(parol:char; var c0,c1:real):real;
var k,n:integer;
    d,
    sum:real;
begin
sum:=0.0;
n:=0;
for k:=1 to nsms do
if types[k]=parol then
begin
d:=pa[k]-(c0+c1*dcw[k]);
sum:=sum+abs(d);
inc(n);
end; // k
if n>3 then MAE:=(sum/(n))
       else MAE:=0.0;
end; // MAE

function MAEtotal(var c0,c1:real):real;
var k,n:integer;
    d,
    sum:real;
begin
sum:=0.0;
n:=0;
for k:=1 to nsms do
if (types[k]=Train) or (types[k]=Calib) or (types[k]=test) then
begin
d:=pa[k]-(c0+c1*dcw[k]);
sum:=sum+abs(d);
inc(n);
end; // k
if n>3 then MAEtotal:=(sum/(n))
       else MAEtotal:=0.0;
end; // MAEtotal



function See2(parol:char; var c0,c1:real; var DCW,PA:DCWPA;var types:TRNCLBTST):real;
var k,n:integer;
    d,
    sum:real;
begin
sum:=0.0;
n:=0;
for k:=1 to nsms do
if types[k]=parol then
begin
d:=pa[k]-(c0+c1*dcw[k]);
sum:=sum+sqr(d);
inc(n);
end; // k
if n>3 then see2:=sqrt(sum/(n-1))
       else see2:=0.0;
end; // see2


function kfkr(parol:char;var x,y:DCWPA;var types:TRNCLBTST; var n:integer):real;
Label outof;
var k:integer;
    a,b,rez,
    sx,sx2,sy,sy2,sxy:extended;         //        October30,2024 to avoid crach CCCP
begin
rez:=0;
sx:=0; sx2:=0; sy:=0; sy2:=0; sxy:=0;
n:=0;
for k:=1 to nsms do
if types[k]=parol then
begin
inc(n);
sx:=sx+ x[k];
sx2:=sx2+sqr(x[k]);
sy:=sy+ y[k];
sy2:=sy2+sqr(y[k]);
sxy:=sxy+x[k]*y[k];
end; // k
if n=0 then goto outof;
a:=(n*sxy-sx*sy);
b:=sqrt( (n*sx2-sqr(sx))* (n*sy2-sqr(sy)) );
if abs(b)>10.0e-22 then rez:=a/b else rez:=0;
outof:
kfkr:=rez;
end; // kfkr


function kfkrCAS(parol:char;nongrata:integer;var x,y:DCWPA;var types:TRNCLBTST; var n:integer):real;
Label outof;
var k:integer;
    a,b,rez,
    sx,sx2,sy,sy2,sxy:real;
begin
rez:=0;
sx:=0; sx2:=0; sy:=0; sy2:=0; sxy:=0;
n:=0;
for k:=1 to nsms do
if types[k]=parol then
if k<>NonGrata then
begin
inc(n);
sx:=sx+ x[k];
sx2:=sx2+sqr(x[k]);
sy:=sy+ y[k];
sy2:=sy2+sqr(y[k]);
sxy:=sxy+x[k]*y[k];
end; // k
if n=0 then goto outof;
a:=(n*sxy-sx*sy);
b:=sqrt( (n*sx2-sqr(sx))* (n*sy2-sqr(sy)) );
if abs(b)>10.0e-22 then rez:=a/b else rez:=0;
outof:
kfkrCAS:=rez;
end; // kfkrCAS

function IIC(parol:char; var c0,c1:real; var DCW,PA:DCWPA;var types:TRNCLBTST):real;
label outof;
var k,
    n_maket,
    nplus,
    nminus:integer;
    rez, rez2,
    d,
    maxDplus,maxDminus,
    plus,minus:real;
begin

plus:=0.0;
minus:=0.0;
nplus:=0;
nminus:=0;
maxDplus:=-10.0e22;
maxDminus:=-10.0e22;

for k:=1 to nsms do
if types[k]=parol then
begin
 d:=pa[k]-(c0+c1*dcw[k]);
 if d>0 then
  begin
   plus:=plus+d;
   inc(nplus);
   if maxDplus<d then maxDplus:=d;
  end
  else
  begin
    minus:=minus-d;
    inc(nminus);
    if maxDminus<abs(d) then maxDminus:=abs(d);
  end;
end; // k

if (nplus=0) or (nminus=0) then
begin
nplus:=nplus+1;
nminus:=nminus+1;
//showmessage('Crakh in IIC: [N minus]=0 or [N plus]=0');
//rez:=0; goto outof;
end; //

plus:=plus/nplus;
minus:=minus/nminus;

if plus>minus then rez:=minus/plus
              else rez:=plus/minus;

outof:
IIC:=rez*kfkr(parol,dcw,pa,types,n_maket);

end; // Index of Ideality of correlation IIC

function CCI(parol:char; var c0,c1:real; var x,y:DCWPA;var types:TRNCLBTST):real;
label outof;
var k,
    nR2 :integer;
    r2,
    delta,
    sum:real;
begin

r2:= sqr( kfkr (parol,  x,y,types,nR2) );

sum:=0.0;
for k:=1 to nsms do
if types[k]=parol then
begin
delta:= sqr( kfkrCAS(types[k],k,x,y,types,nR2) ) - r2;
if delta>0.0 then sum:=sum + delta;
end; // k

//ICC:= 1.0 + minus;

CCI:=  1.0 - sum;

end; // Correlation Intensity Index CII (May17,2022)


procedure saveCWs(namefile:string);
var k:integer;
    f:textfile;
begin
assign(f,namefile);
rewrite(f);
for k:=1 to n_glb do writeln(f,cw[1,k]:9:5);
closefile(f);
end; // save CWs

function iks(x0,rx:integer;min,max,x:real):integer;// calculation of X-position
begin
iks:=x0+trunc( ((x-min)/(max-min))*rx);
end; // iks

function igrek(y0,ry:integer;min,max,y:real):integer;//calculation of Y-position
begin
igrek:=y0-trunc(  ((y-min)/(max-min))*ry);
end; // igrek

procedure minmax(var x:DCWPA;var min,max:real);
var k:integer;
begin

//if do_vld then showmessage('Minmax: '+inttostr(nsms));

min:=x[1];
max:=x[1];
for k:=1 to nsms do
// if (types[k]=Train) or (types[k]=Calib) or (types[k]=Test) or (types[k]=Valid)then
begin
if x[k]>=max then max:=x[k];
if x[k]<=min then min:=x[k];
end; // k
end; // minmax

procedure CASpause;
var i,j,k:integer;
begin
// for i:=1 to 10000 do for j:=1 to 10000 do k:=k;
end;  // CASpause

procedure dodot(x1,y1:integer);
     var d,k:Integer;
begin

k:=dotsize+1;
for d:=1 to k do
begin
   form1.Canvas.MoveTo(x1,y1);
   form1.Canvas.LineTo(x1,y1);
   form1.Canvas.LineTo(x1+d,y1);  // Jun 10, 2023
   form1.Canvas.LineTo(x1+d,y1+d);
   form1.Canvas.LineTo(x1,y1+d);
   form1.Canvas.LineTo(x1,y1);
end; // d
end; // dodot


function RGindex(parol:char;var x,y:DCWPA):Real;
var k,nr2,
    nred,ngreen:Integer;
    r2,r2k,
    delta,
    rez,
    r2red,r2green:Real;
    red,green:Char;
begin
red:='r';
green:='g';

//nred:=0;
//ngreen:=0;

     for k:=1 to nsms do types2[k]:='$';

//     assign(re,'!red.txt'); rewrite(re);
//     assign(gr,'!green.txt'); rewrite(gr);

     for k:=1 to nsms do
     if types[k]=parol then
     begin
      r2 :=sqr( kfkr   (types[k],   x,y,types,nR2) );
      r2k:=sqr( kfkrCAS(types[k],k,x,y,types,nR2) );

      delta:= r2 - r2k;

     if delta>0
     then
       begin
//       writeln(gr,types[k],CAS[k],' ',sms[k],x[k]:9:3);
       types2[k]:=green;
//       inc(ngreen);
       end // green
     else
     begin
//       writeln(re,types[k],CAS[k],' ',sms[k],x[k]:9:3);
       types2[k]:=red;
//       inc(nred);
     end; //g
     end;

     r2red   := ( kfkr(red  ,x,y,types2,nred   ));
     r2green := ( kfkr(green,x,y,types2,ngreen ));

//if (nred<=0) or (ngreen<=0)
//then rez:=0 else rez:=trunc(r2red/r2green);

if (abs(r2green)>0.0001)
then rez:=r2red / r2green
else rez:=0.0;


RGindex:=rez;
end; // RGindex January24,2024

procedure savetypes;
var k:integer;
    f:text;
begin
assign(f,'types.txt'); rewrite(f);
for k:=1 to nsms do writeln(f,types[k]);
close(f);
end; // savetypes

procedure loadtypes;
var k:integer;
    f:text;
begin
assign(f,'types.txt'); reset(f);
for k:=1 to nsms do readln(f,types[k]);
close(f);
end; // savetypes


procedure showCAS(parol:char;var x,y:DCWPA);
label outof,nextk;
var
     x1,y1,x2,y2,
     kk,
     k,x0,y0:integer;
//     mnx,mxx,
//     mny,mxy:real;
     subset,
     vector,
     txt:string;
     nR2,
     r:integer;
     delta, // R2 current minus R2 (without k-th)
     C0,C1:real;
     re,gr:text;
     f:text;
     r2red,r2green:real;
     nred,ngreen:integer;
     red,green:char;
begin

red:='r';
green:='g';

//if RedGreen then showmessage('nsms='+intToStr(nsms));

C0:=StrToFloat(form1.Edit4.Text);
C1:=StrToFloat(form1.Edit5.Text);

if nsms=0 then
begin
messageDlg(
'There are not data: '
+#13+
'Only after building up a model you can study its graphical representation',
mtConfirmation, [mbOK],0);
goto outof;
end; // nsms = 0

minmax(x,mnx,mxx);
minmax(y,mny,mxy);

kk:=0;
CASdelta:=1;

if switch012=0 then kk:=-1;

k:=0;
repeat k:=k+CASdelta;

if kk<>-1 then kk:=kk+CASdelta;

if k<1 then k:=nsms;
if k>nsms then k:=1;

if kk<>-1 then k:=kk;

if types[k]<>GraphParol then goto nextk;
if types[k]=Train then begin x0:=x10;y0:=y10;  end;
if types[k]=Calib then begin x0:=x20;y0:=y20;  end;
if types[k]=Test  then begin x0:=x30;y0:=y30;  end;
if types[k]=Valid then begin x0:=x40;y0:=y40;  end;

x1:=iks  (x0,rx,minx,maxx,(x[k]-mnx)/(mxx-mnx));
y1:=igrek(y0,ry,miny,maxy,(y[k]-mny)/(mxy-mny));

//form1.Canvas.Pen.Color:=clwhite;
//form1.Canvas.Pen.Color:=clAqua;
//form1.Canvas.Pen.Color:=clLime;

If not RedGreen then begin form1.Canvas.Pen.Color:=clRed; dodot(x1,y1); end; // May11,2023

if RedGreen then
begin
if x[k]>c0+c1*y[k] then form1.Canvas.Pen.Color:=clLime;
if x[k]<c0+c1*y[k] then form1.Canvas.Pen.Color:=clRed;
dodot(x1,y1);
end;

//dodot(x1,y1); // Jan 11, 2018

(*
form1.Canvas.MoveTo(x1,y1);
form1.Canvas.LineTo(x1+0,y1+1);
form1.Canvas.LineTo(x1+1,y1+1);
form1.Canvas.LineTo(x1+1,y1+0);
form1.Canvas.LineTo(x1+0,y1+0);
form1.Canvas.LineTo(x1+0,y1+2);
form1.Canvas.LineTo(x1+2,y1+2);
form1.Canvas.LineTo(x1+2,y1+0);
form1.Canvas.LineTo(x1+0,y1+0);
*)
CASpause;

if CASdelta<0 then vector:='decrease ' else Vector:='increase ';

if types[k]=Train then begin subset:='Active Training set'  end;
if types[k]=Calib then begin subset:='Passive Training set'  end;
if types[k]=Test  then begin subset:='Calibration set'  end;
if types[k]=Valid then begin subset:='Validation set'  end;

delta:=
sqr( kfkrCAS(types[k],k,x,y,types,nR2) ) -
sqr( kfkr   (types[k],  x,y,types,nR2) );

txt:=
subset+#13+#13+
//'Type='+types[k]+#13+
'Number='+IntToStr(k)+ //#13+
'  ID ='+cas[k]+#13+
'Expr='+floatToStrF(x[k],FFfixed,9,4)+
'  Calc='+ floatToStrF(C0+C1*y[k],FFfixed,9,4)+
'  Delta='+ floatToStrF(x[k]-(C0+C1*y[k]),FFfixed,9,4)+#13+
'R2 ='+FloatToStrF(sqr( kfkr   (types[k],  x,y,types,nR2) ),FFfixed,7,4)+
' R2*='+FloatToStrF(sqr( kfkrCAS(types[k],k,x,y,types,nR2) ),FFfixed,7,4)+
' dR='+FloatToStrF(delta,FFfixed,7,4)+#13+
'To continue '+vector+' ?';



if (kk = -1) then
   begin
        if switch012<>0 then
        Begin
        ShowMessage('The image of two correlation clusters');
        goto OutOf;
        end; // switch012<>0


   r:=messageDlg(txt,mtConfirmation,[mbYes,mbNo,mbCancel],0);
   if r=mrNO then CASdelta:=-CASdelta;
   if r=mrCancel then
   begin
   form1.Canvas.Pen.Color:=clblack; dodot(x1,y1);
//   if not RedGreen then begin form1.Canvas.Pen.Color:=clblack; dodot(x1,y1);end;
   goto outof;
   end // r=mrcancel
   else if not RedGreen then begin form1.Canvas.Pen.Color:=clblack; dodot(x1,y1);end; // May11,2023
end; // kk = -1

(*
form1.Canvas.MoveTo(x1,y1);
form1.Canvas.LineTo(x1+0,y1+1);
form1.Canvas.LineTo(x1+1,y1+1);
form1.Canvas.LineTo(x1+1,y1+0);
form1.Canvas.LineTo(x1+0,y1+0);

form1.Canvas.LineTo(x1+0,y1+2);
form1.Canvas.LineTo(x1+2,y1+2);
form1.Canvas.LineTo(x1+2,y1+0);
form1.Canvas.LineTo(x1+0,y1+0);
*)


nextk:

if kk>=nsms then kk:=-1;

until r=mrCancel;
outof:
// October 27,2021 up-model is red, down-model is green

//if RedGreen then
//begin // May11,2023
//r:=messageDlg('Save +delta (green) and -delta (red) ?',mtConfirmation,[mbYes,mbNo],0);
//if r=mrYes then
begin

     savetypes;

     assign(re,'!red.txt'); rewrite(re);
     for k:=1 to nsms do
     if types[k]=parol then
     begin
     if x[k]<c0+c1*y[k] then
       begin
       writeln(re,types[k],CAS[k],' ',sms[k],x[k]:9:3);
       types[k]:=red;
       end; // red
     end;
     close(re);
     assign(gr,'!green.txt'); rewrite(gr);
     for k:=1 to nsms do
     if types[k]=parol then
     begin
     if x[k]>c0+c1*y[k] then
       begin
       writeln(gr,types[k],CAS[k],' ',sms[k],x[k]:9:3);
       types[k]:=green;
       end; //g
     end;
     close(gr);
     // october 28,2021
     r2red   := sqr( kfkr(red  ,x,y,types,nred   ));
     r2green := sqr( kfkr(green,x,y,types,ngreen ));


     showmessage
     (
      'Red R2 = '  +FloatToStrF( r2red  ,FFfixed,9,4)+' n='+ IntToStr(nred)+#13+
      'Green R2 = '+FloatToStrF( r2green,FFfixed,9,4)+' n='+ IntTostr(ngreen)
     );

loadtypes;

end; // yes save files red.txt and green.txt
//end; // not RedGreen May11,2023

end; // showCAS

procedure showCAS2(parol:char;var x,y:DCWPA);
label outof,nextk;
var
     x1,y1,x2,y2,
     kk,
     k,x0,y0:integer;
//     mnx,mxx,
//     mny,mxy:real;
     subset,
     vector,
     txt:string;
     nR2,
     r:integer;
     delta, // R2 current minus R2 (without k-th)
     r2,
     r2k,
     C0,C1:real;
     re,gr:text;
     f:text;
     r2red,r2green:real;
     nred,ngreen:integer;
     red,green:char;
begin

red:='r';
green:='g';

//if RedGreen then showmessage('nsms='+intToStr(nsms));

C0:=StrToFloat(form1.Edit4.Text);
C1:=StrToFloat(form1.Edit5.Text);

if nsms=0 then
begin
messageDlg(
'There are not data: '
+#13+
'Only after building up a model you can study its graphical representation',
mtConfirmation, [mbOK],0);
goto outof;
end; // nsms = 0

minmax(x,mnx,mxx);
minmax(y,mny,mxy);

k:=0;
repeat k:=k+CASdelta;

if kk<>-1 then kk:=kk+CASdelta;

if k<1 then k:=nsms;
if k>nsms then k:=1;

if kk<>-1 then k:=kk;



if types[k]<>GraphParol then goto nextk;
if types[k]=Train then begin x0:=x10;y0:=y10;  end;
if types[k]=Calib then begin x0:=x20;y0:=y20;  end;
if types[k]=Test  then begin x0:=x30;y0:=y30;  end;
if types[k]=Valid then begin x0:=x40;y0:=y40;  end;

x1:=iks  (x0,rx,minx,maxx,(x[k]-mnx)/(mxx-mnx));
y1:=igrek(y0,ry,miny,maxy,(y[k]-mny)/(mxy-mny));

//form1.Canvas.Pen.Color:=clwhite;
//form1.Canvas.Pen.Color:=clAqua;
//form1.Canvas.Pen.Color:=clLime;

If not RedGreen then begin form1.Canvas.Pen.Color:=clRed; dodot(x1,y1); end; // May11,2023

if RedGreen then
begin
//if x[k]>c0+c1*y[k] then form1.Canvas.Pen.Color:=clLime;
//if x[k]<c0+c1*y[k] then form1.Canvas.Pen.Color:=clRed;

delta:=
( kfkr   (types[k],  x,y,types,nR2) ) -
( kfkrCAS(types[k],k,x,y,types,nR2) );

if delta>0 then form1.Canvas.Pen.Color:=clLime
           else form1.Canvas.Pen.Color:=clRed;



dodot(x1,y1);
end;



//dodot(x1,y1); // Jan 11, 2018

CASpause;

if CASdelta<0 then vector:='decrease ' else Vector:='increase ';

if types[k]=Train then begin subset:='Active Training set'  end;
if types[k]=Calib then begin subset:='Passive Training set'  end;
if types[k]=Test  then begin subset:='Calibration set'  end;
if types[k]=Valid then begin subset:='Validation set'  end;

txt:=
subset+#13+#13+
//'Type='+types[k]+#13+
'Number='+IntToStr(k)+ //#13+
'  ID ='+cas[k]+#13+
'Expr='+floatToStrF(x[k],FFfixed,9,4)+
'  Calc='+ floatToStrF(C0+C1*y[k],FFfixed,9,4)+
'  Delta='+ floatToStrF(x[k]-(C0+C1*y[k]),FFfixed,9,4)+#13+
'R ='+FloatToStrF(( kfkr   (types[k],  x,y,types,nR2) ),FFfixed,7,4)+
' R*='+FloatToStrF(( kfkrCAS(types[k],k,x,y,types,nR2) ),FFfixed,7,4)+
' R-R*='+FloatToStrF(delta,FFfixed,7,4)+#13+
'To continue '+vector+' ?';

//if switch012<>0 then txt:= subset+#13+#13+'Continue study dots?';

if kk=-1 then
begin
  ShowMessage('The oppositionists (red) and supporters (green) of the correlation');
//   r:=messageDlg(txt,mtConfirmation,[mbYes,mbNo],0);
//   if (r=mrYES) or (r=mrNO) then
//   begin
   //form1.Canvas.Pen.Color:=clblack; dodot(x1,y1);
   //if not RedGreen then begin form1.Canvas.Pen.Color:=clblack; dodot(x1,y1);end;
   goto outof;
//   end // r=mrcancel
//   else if not RedGreen then begin form1.Canvas.Pen.Color:=clblack; dodot(x1,y1);end; // May11,2023
end; // kk=-1

nextk:

if kk>=nsms then kk:=-1;

until r=mrCancel;
outof:
// October 27,2021 up-model is red, down-model is green

if RedGreen then
begin // May11,2023
//r:=messageDlg('Save +delta (green) and -delta (red) ?',mtConfirmation,[mbYes,mbNo],0);
//if r=mrYes then
begin



     for k:=1 to nsms do types2[k]:='$';

//     assign(re,'!red.txt'); rewrite(re);
//     assign(gr,'!green.txt'); rewrite(gr);

     for k:=1 to nsms do
     if types[k]=parol then
     begin
      r2 :=( kfkr   (types[k],   x,y,types,nR2) );
      r2k:=( kfkrCAS(types[k],k,x,y,types,nR2) );

      delta:= r2 - r2k;

     if delta>0
     then
       begin
//       writeln(gr,types[k],CAS[k],' ',sms[k],x[k]:9:3);
       types2[k]:=green;
       end // green
     else
     begin
//       writeln(re,types[k],CAS[k],' ',sms[k],x[k]:9:3);
       types2[k]:=red;
     end; //g
     end;

//     close(re);
//     close(gr);
     // october 28,2021

//    showmessage('close re gr...');
     r2red   := ( kfkr(red  ,x,y,types2,nred   ));
     r2green := ( kfkr(green,x,y,types2,ngreen ));


     showmessage
     (
      'Red R2 = '  +FloatToStrF( r2red  ,FFfixed,9,4)+' n='+ IntToStr(nred)+#13+
      'Green R2 = '+FloatToStrF( r2green,FFfixed,9,4)+' n='+ IntTostr(ngreen)+#13+
      'CCCP (red R2/green R2) = '+ FloatToStrF( RGindex(parol,x,y),FFfixed,9,4)
     );


end; // yes save files red.txt and green.txt
end; // not RedGreen May11,2023

end; // showCAS2


procedure TPTNFPFN(parole:char; var TP1,TN1,FP1,FN1:integer);
var k:integer;
    TP,TN,FP,FN : real;
begin

TP:=0;
TN:=0;
FP:=0;
FN:=0;

for k:=1 to nsms do
if types[k]=parole then
begin
if (PAcalc[k]>=middle01) then if (pa01[k]>middle01) then TP:=TP+1
                                                    else FP:=FP+1;
if (PAcalc[k]<=middle01) then if (pa01[k]<middle01) then TN:=TN+1
                                                    else FN:=FN+1;

end; // k

TP1:=Trunc(TP);
TN1:=Trunc(TN);
FP1:=Trunc(FP);
FN1:=Trunc(FN);

end; // TPTNFPFN(parol, TP,TN,FP,FN)

procedure form1CanvasTextOut(x,y:integer;txt:string);
begin
form1.Canvas.TextOut(x-15,y,'.             .');
form1.Canvas.TextOut(x-15,y,txt);
end; // form1canvasTextOut



procedure tct(x0,y0:integer);
label outof;
const d17 = 30;
var x1,y1,x2,y2:integer;
//    tps,tns,fps,fns:string;

begin
if show_optimiz then goto OutOf;    //October16,2024

x1:=iks  (x0,rx,minx,maxx,0);
y1:=igrek(y0,ry,miny,maxy,0);

x2:=iks  (x0,rx,minx,maxx,maxx);
y2:=igrek(y0,ry,miny,maxy,maxy);


form1.Canvas.MoveTo(x1,y1); form1.Canvas.LineTo(x2,y1);
form1.Canvas.MoveTo(x2,y1); form1.Canvas.LineTo(x2-7,y1-4);
form1.Canvas.MoveTo(x2,y1); form1.Canvas.LineTo(x2-7,y1+4);

form1.Canvas.MoveTo(x1,y1); form1.Canvas.LineTo(x1,y2);
form1.Canvas.MoveTo(x1,y2); form1.Canvas.LineTo(x1-4,y2+7);
form1.Canvas.MoveTo(x1,y2); form1.Canvas.LineTo(x1+4,y2+7);

if form1.CheckBox17.Checked then
begin

TNs:='TN='+IntToStr(TN);
TPs:='TP='+IntToStr(TP);
FPs:='FP='+IntToStr(FP);
FNs:='FN='+IntToStr(FN);

if show_TPTNFPFN then
begin
 form1CanvasTextOut(x0+rx div 4,         y0-ry div 3,TNs);
 form1CanvasTextOut(x0+rx div 2+rx div 4,y0-ry div 3,FNs);
 form1CanvasTextOut(x0+rx div 4,         y0-ry div 2 - ry div 4,FPs);
 form1CanvasTextOut(x0+rx div 2+rx div 4,y0-ry div 2 - ry div 4,TPs);
end; // show_TPTNFPFN

end;

// July10,2023

//form1.Canvas.TextOut(x1+160,y1-5,'Observed');
form1.Canvas.TextOut(x1+130,y1+7,'EXPERIMENT');

form1.Canvas.TextOut(x1+163,y1-9,'X');

(**)
form1.Canvas.TextOut(x1-d17+17,y2-3, 'Y');

form1.Canvas.TextOut(x1-d17-1,y2, 'M');
form1.Canvas.TextOut(x1-d17  ,y2+12,'O');
form1.Canvas.TextOut(x1-d17  ,y2+24,'D');
form1.Canvas.TextOut(x1-d17  ,y2+36,'E');
form1.Canvas.TextOut(x1-d17+1,y2+48,'L');
(**)

outof: //October16,2024

end; //tct ( Training Calibration Test - AXES )

Procedure drawaxes; // drawing of axes of coordinates
var x1,y1,x2,y2:integer;
    YesNo:boolean;
begin

// YesNo:=form1.CheckBox17.Checked;
YesNo:=classification;

form1.Canvas.Pen.Color:=clBlack;
form1.Canvas.Pen.Style:=psSolid;

if yesno then TPTNFPFN(train,TP,TN,FP,FN);
tct(x10,y10);
if yesno then TPTNFPFN(calib,TP,TN,FP,FN);
tct(x20,y20);
if yesno then TPTNFPFN(test ,TP,TN,FP,FN);
tct(x30,y30);
if do_vld then
begin
if yesno then TPTNFPFN(valid,TP,TN,FP,FN);
tct(x40,y40);
end; // do VLD

end; // drawaxes


function CWsNameSame(var name1,name2:CWsName):boolean;
label rez;
var k:integer; test:boolean;
begin
test:=true;
for k:=1 to MaxCharSF do
if name1[k]<>Name2[k] then begin test:=False; goto rez; end;
rez:
CWsNameSame:=test;
end; // CWsNameSame

function CWnumber(var name:CWsName; nglb:integer):integer;
Label bye;
var k,rez:integer;
begin
rez:=0;
for k:=1 to nglb do
if CWsNameSame(Global_SF_list[k],name) then begin rez:=k; goto bye; end;

bye:
CWnumber:=rez;
end; // CWNumber

function NaturalCW(var nameSF:CWsname;var No:integer):real;
Label outof;
var k:integer;
    rez:real;
begin

if dir='model/' then
if probe<>1 then
begin
showmessage('NaturalCW, probe='+inttostr(probe)+' Now halt');
halt;
end;


rez:=off;
No:=0;
if n_glb<3 then ShowMessage('Data is not correct: the number of SMILES attributes less than 3');
for k:=1 to n_glb do
if CWsNameSame(nameSF,Global_SF_list[k]) then
begin
No:=k;
rez:=CW[probe,k];
goto outof;
end; // k
outof:
NaturalCW:=rez;
end; // NaturalCW

function digit(x:char):boolean;
begin
digit:=( x in ['0','1','2','3','4','5','6','7','8','9'] );
end; // digit

function cri(var x:CWsName):real;
var k:integer; mult,add,sum,dec:real;  mss:string; ch:char;
begin
dec:=1.0;
sum:=0.0;

add:=0.0;

//          if x[5]<>BAR then add:=10e14;
//          if x[9]<>BAR then add:=10e22;

for k:=MaxCharSF downto 1 do
begin

//mss:=mss + ' '+x[k]+' '+intToStr(ord(x[k]));
//messageDLg(mss,mtInformation,[mbOK],0);

dec:=dec*10.0;

mult := trunc(ord(x[k]));

//ch:=x[k];
//if digit(ch) then mult:=mult*0.1;
//if x[k]='.' then mult:=trunc(ord('9'));

sum:=sum + dec * mult;

end; // k
cri:=sum + add;
end; // cri

procedure order_Global_SF_list;
var t,k,j,maxk:integer; reg:CWsName; max:real;
begin
for k:=1 to n_glb-1 do
begin
max:=cri( Global_SF_list[k] );
maxk:=k;
for j:=k to n_glb   do
if cri( global_SF_list[j] ) < max then
begin
max:=cri( global_SF_list[j] );
maxk:=j;
end; // cri>max

for t:=1 to MaxCharSF do reg[t]:=global_SF_list[k][t];
for t:=1 to MaxCharSF do Global_sf_list[k][t]:=Global_sf_list[maxk][t];
for t:=1 to MaxCharSF do global_sf_list[maxk][t]:=reg[t];

end; // k

end; // order_Global_SF_list

procedure do_Global_SF_list(
var local:sflist;
var nloc:integer;
var global:sflist;
var nglb:integer);

label nextloc;
var kk,k,loc,glb:integer;

begin

// showmessage('Start of DO_GLOBAL_SF_LIST nglb='+inttostr(nglb));

if nglb=0 then
begin
nglb:=1;
for k:=1 to MaxCharSF do global[nglb][k]:=local[1][k];
if IniCWs then CW[probe,1]:=StartValue;
end; // nglb=0

for loc:=1 to nloc do
begin
for glb:=1 to nglb do
if CWsNameSame(local[loc],global[glb])then goto nextloc;

inc(nglb);

if nglb>MaxSF then
begin
showmessage('Too much CWs!' + 'Limit is '+ IntToStr(MaxSF)+' Program will be halted');
halt;
end;

for k:=1 to MaxCharSF do global[nglb][k]:=local[loc][k];
if IniCWs then cw[probe,nglb]:=StartValue;

nextloc:
end; // nextloc

if not model_is_loaded then order_Global_SF_list;

//showmessage('GLOBAL LIST IS READY');

end; // Do_Global_SF_list

procedure read_sms(var f:textfile;var typeset:char;var cas,sms,chana:string; var pa:real;ksms:integer);
var
    c,            // variable for reading chars
    colon:char;   // colon between typeset (+/-) and SMILIES
    help,
    show:string;  // string for mesages
    k:integer;
    txt:string;  r:integer; // for messageDLG()
begin

read(f,typeset);      // April3,2024    if typeset='*' then typeset:=test;

if (typeset<>Train) and (typeset<>Calib) and (typeset<>test) and (typeset<>valid)then
begin
showmessage(
'Something is wrong in File '+form1.edit1.text + #13+
'Program will be halted');
Halt;
end; // bad SMILES string

CAS:='';
k:=0;
repeat inc(k);
read(f,c);  if c<>' ' then CAS:=CAS+c;
until c=' ';

// ShowMessage(IntToStr(k)+' '+cas);

sms:='';
repeat
read(f,c);

if (c=BAR)
or (c='*')
//or (c='%')

then
begin
c:=reBAR;

//form1.CheckBox32.Checked:=false;
//form1.CheckBox30.Checked:=false;
//form1.CheckBox29.Checked:=false;
//form1.CheckBox31.Checked:=false;
//form1.CheckBox9.Checked:=false;
//form1.CheckBox28.Checked:=false;
//form1.CheckBox18.Checked:=false;
//form1.CheckBox10.Checked:=false;

DotInSMILES:=
'Attention! Some SMILES are containing dot (i.e. "."); Dots are replaced by "'+c+'"';

if Form1.CheckBox32.Checked then
begin
(**)
txt:=
' The compound with CAS '+cas+' contains ["." or "*" or "%"].'+#13+
' Translation of SMILES into graph can be wrong.'+#13+
' Please use method based on solely SMILES or delete compound with CAS'+' '+cas;

showmessage(txt);
halt;
(**)
Form1.Label81.visible:=True;
//form1.label81.Caption:='Zero-order bond in graph!';
//form1.Label81.Visible:=True;
//form1.Label81.Font.Size:=12;
//form1.Label81.Font.Color:=clred;



end; // Check box 32 = GRAPH

end;

if c<>' ' then sms:=sms+c;

if length(sms)>MaxSMILESLength then
ShowMessage('Too large SMILES:'+#13+' CAS='+cas+#13+inttostr(k));
until c=' ';

sms:=sms+BCE;

//ShowMessage(typeset+' '+IntToStr(k)+' '+cas+' '+sms);
//ShowMessage(typeset+' '+cas+' '+sms);


// readln(f,pa);

read(f,pa);


readln(f);

end; //read_SMS


procedure do_classification(parole:char;
var sensitivity, specificity, accuracy, MCC:double;
var TP1,TN1,FP1,FN1:integer);
label outoff;
var k:integer;
    denominator:double;
    TP,TN,FP,FN : real;
begin

TP:=0;
TN:=0;
FP:=0;
FN:=0;

if (parole=Calib) and (form1.RadioButton2.Checked) then
begin
sensitivity:=0;
specificity:=0;
accuracy:=0;
MCC:=0;
exit;
end;


for k:=1 to nsms do
if types[k]=parole then
begin
(*
*)
if (PAcalc[k]>=middle01) then if (pa01[k]>middle01) then TP:=TP+1
                                                    else FP:=FP+1;
if (PAcalc[k]< middle01) then if (pa01[k]<middle01) then TN:=TN+1
                                                    else FN:=FN+1;

end; // k

if (TP=0) or (TN=0) then
begin
//showmessage('The calculation of sensitivity, specificity, and accuracy is impossible');
goto outoff;
end; // TP=0, TN=0

sensitivity:=TP / (TP+FN); // Aug2,2024 sens & spec defined according Wikipedia

specificity:=TN / (TN+FP);

accuracy   :=(TP + TN) / (TP+TN+FP+FN);

denominator:= sqrt( (TP+FP)*(TP+FN)*(TN+FP)*(TN+FN) );

If abs(denominator)>10.0e-22
then MCC := (TP*TN - FP*FN) / denominator
else MCC := 0;

outoff:

TP1:=Trunc(TP);
TN1:=Trunc(TN);
FP1:=Trunc(FP);
FN1:=Trunc(FN);

end; // do_classification


procedure c1c2c3c4(var x:string;var c1,c2,c3,c4:char; var n:integer);
label outof;
begin

c1:=x[n];

if c1=')' then c1:='(';
//if c1=']' then c1:='[';
if c1=BCE then c1:=BAR;

c2:=BAR;
c3:=BAR;
c4:=BAR;

if x[n]='%' then
begin
if digit(x[n+1]) then c2:=x[n+1];
if digit(x[n+2]) then c3:=x[n+2];
end; // % digit + 1 + digit 2

// if (x[n]='h') then begin c2:=x[n+1]; c3:=x[n+2]; end; ??? InChI ...
// if (x[n]='H') then c2:=x[n+1];

if (x[n]='@') and (x[n+1]='@') then c2:=x[n+1];


if (x[n]='C') and (x[n+1]='l') then c2:=x[n+1];
if (x[n]='B') and (x[n+1]='r') then c2:=x[n+1];

if (x[n]='N') and (x[n+1]='i') then c2:=x[n+1];
if (x[n]='Z') and (x[n+1]='n') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='l') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='u') then c2:=x[n+1];
if (x[n]='Z') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='s') then c2:=x[n+1];
if (x[n]='F') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='H') and (x[n+1]='g') then c2:=x[n+1];
if (x[n]='M') and (x[n+1]='n') then c2:=x[n+1];
if (x[n]='N') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='M') and (x[n+1]='g') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='r') then c2:=x[n+1];

if (x[n]='B') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='B') and (x[n+1]='i') then c2:=x[n+1];

if (x[n]='C') and (x[n+1]='s') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='o') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='u') then c2:=x[n+1];
if (x[n]='G') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='M') and (x[n+1]='o') then c2:=x[n+1];

if (x[n]='P') and (x[n+1]='t') then c2:=x[n+1];
if (x[n]='L') and (x[n+1]='i') then c2:=x[n+1];

if (x[n]='R') and (x[n+1]='b') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='d') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='g') then c2:=x[n+1];


if (x[n]='S') and (x[n+1]='b') then c2:=x[n+1];
if (x[n]='S') and (x[n+1]='i') then c2:=x[n+1];

if (x[n]='T') and (x[n+1]='l') then c2:=x[n+1];

// if (x[n]='S') and (x[n+1]='c') then c2:=x[n+1]; No 'Sc'
if (x[n]='T') and (x[n+1]='i') then c2:=x[n+1];
if (x[n]='G') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='S') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='S') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='c') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='u') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='h') then c2:=x[n+1];
if (x[n]='P') and (x[n+1]='d') then c2:=x[n+1];
if (x[n]='I') and (x[n+1]='n') then c2:=x[n+1];
if (x[n]='S') and (x[n+1]='n') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='B') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='N') and (x[n+1]='b') then c2:=x[n+1];

if (x[n]='H') and (x[n+1]='f') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='O') and (x[n+1]='s') then c2:=x[n+1];
if (x[n]='I') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='P') and (x[n+1]='b') then c2:=x[n+1];

if (x[n]='P') and (x[n+1]='o') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='t') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='f') then c2:=x[n+1];
if (x[n]='F') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='a') then c2:=x[n+1];

if (x[n]='D') and (x[n+1]='b') then c2:=x[n+1];
if (x[n]='S') and (x[n+1]='g') then c2:=x[n+1];
if (x[n]='B') and (x[n+1]='h') then c2:=x[n+1];
if (x[n]='H') and (x[n+1]='s') then c2:=x[n+1];

if (x[n]='M') and (x[n+1]='t') then c2:=x[n+1];
if (x[n]='D') and (x[n+1]='s') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='g') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='l') then c2:=x[n+1];

if (x[n]='H') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='N') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='K') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='X') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='R') and (x[n+1]='n') then c2:=x[n+1];

if (x[n]='L') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='e') then c2:=x[n+1];
if (x[n]='P') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='N') and (x[n+1]='d') then c2:=x[n+1];
if (x[n]='P') and (x[n+1]='m') then c2:=x[n+1];
if (x[n]='S') and (x[n+1]='m') then c2:=x[n+1];
if (x[n]='E') and (x[n+1]='u') then c2:=x[n+1];
if (x[n]='G') and (x[n+1]='d') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='b') then c2:=x[n+1];
if (x[n]='D') and (x[n+1]='y') then c2:=x[n+1];
if (x[n]='H') and (x[n+1]='o') then c2:=x[n+1];
if (x[n]='E') and (x[n+1]='r') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='m') then c2:=x[n+1];
if (x[n]='Y') and (x[n+1]='b') then c2:=x[n+1];
if (x[n]='L') and (x[n+1]='u') then c2:=x[n+1];

if (x[n]='A') and (x[n+1]='c') then c2:=x[n+1];
if (x[n]='T') and (x[n+1]='h') then c2:=x[n+1];
if (x[n]='P') and (x[n+1]='a') then c2:=x[n+1];
if (x[n]='N') and (x[n+1]='p') then c2:=x[n+1];
if (x[n]='P') and (x[n+1]='u') then c2:=x[n+1];
if (x[n]='A') and (x[n+1]='m') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='m') then c2:=x[n+1];
if (x[n]='B') and (x[n+1]='k') then c2:=x[n+1];
if (x[n]='C') and (x[n+1]='f') then c2:=x[n+1];
if (x[n]='E') and (x[n+1]='s') then c2:=x[n+1];
if (x[n]='F') and (x[n+1]='m') then c2:=x[n+1];
if (x[n]='M') and (x[n+1]='d') then c2:=x[n+1];
if (x[n]='N') and (x[n+1]='o') then c2:=x[n+1];
if (x[n]='L') and (x[n+1]='r') then c2:=x[n+1];

if c2=BAR then begin goto outof; end;
inc(n);
if c3=BAR then begin goto outof; end;
inc(n);
if c4=BAR then begin goto outof; end;
inc(n);

outof:
end; // c1c2c3c4


procedure nmr_in_c1c2c3c4(nmr1:integer;var c1,c2,c3,c4:char);
var nmr:integer;
begin
c1:='0'; c2:='0'; c3:='0'; c4:='0';

//if nmr1<0 then c2:='-';
nmr:=abs(nmr1);


if nmr=1 then begin c4:='1'; end;
if nmr=2 then begin c4:='2'; end;
if nmr=3 then begin c4:='3'; end;
if nmr=4 then begin c4:='4'; end;
if nmr=5 then begin c4:='5'; end;
if nmr=6 then begin c4:='6'; end;
if nmr=7 then begin c4:='7'; end;
if nmr=8 then begin c4:='8'; end;
if nmr=9 then begin c4:='9'; end;

if nmr=10 then begin c3:='1'; c4:='0'; end;
if nmr=11 then begin c3:='1'; c4:='1'; end;
if nmr=12 then begin c3:='1'; c4:='2'; end;
if nmr=13 then begin c3:='1'; c4:='3'; end;
if nmr=14 then begin c3:='1'; c4:='4'; end;
if nmr=15 then begin c3:='1'; c4:='5'; end;
if nmr=16 then begin c3:='1'; c4:='6'; end;
if nmr=17 then begin c3:='1'; c4:='7'; end;
if nmr=18 then begin c3:='1'; c4:='8'; end;
if nmr=19 then begin c3:='1'; c4:='9'; end;

if nmr=20 then begin c3:='2'; c4:='0'; end;
if nmr=21 then begin c3:='2'; c4:='1'; end;
if nmr=22 then begin c3:='2'; c4:='2'; end;
if nmr=23 then begin c3:='2'; c4:='3'; end;
if nmr=24 then begin c3:='2'; c4:='4'; end;
if nmr=25 then begin c3:='2'; c4:='5'; end;
if nmr=26 then begin c3:='2'; c4:='6'; end;
if nmr=27 then begin c3:='2'; c4:='7'; end;
if nmr=28 then begin c3:='2'; c4:='8'; end;
if nmr=29 then begin c3:='2'; c4:='9'; end;

if nmr=30 then begin c3:='3'; c4:='0'; end;
if nmr=31 then begin c3:='3'; c4:='1'; end;
if nmr=32 then begin c3:='3'; c4:='2'; end;
if nmr=33 then begin c3:='3'; c4:='3'; end;
if nmr=34 then begin c3:='3'; c4:='4'; end;
if nmr=35 then begin c3:='3'; c4:='5'; end;
if nmr=36 then begin c3:='3'; c4:='6'; end;
if nmr=37 then begin c3:='3'; c4:='7'; end;
if nmr=38 then begin c3:='3'; c4:='8'; end;
if nmr=39 then begin c3:='3'; c4:='9'; end;

if nmr=40 then begin c3:='4'; c4:='0'; end;
if nmr=41 then begin c3:='4'; c4:='1'; end;
if nmr=42 then begin c3:='4'; c4:='2'; end;
if nmr=43 then begin c3:='4'; c4:='3'; end;
if nmr=44 then begin c3:='4'; c4:='4'; end;
if nmr=45 then begin c3:='4'; c4:='5'; end;
if nmr=46 then begin c3:='4'; c4:='6'; end;
if nmr=47 then begin c3:='4'; c4:='7'; end;
if nmr=48 then begin c3:='4'; c4:='8'; end;
if nmr=49 then begin c3:='4'; c4:='9'; end;

if nmr=50 then begin c3:='5'; c4:='0'; end;
if nmr=51 then begin c3:='5'; c4:='1'; end;
if nmr=52 then begin c3:='5'; c4:='2'; end;
if nmr=53 then begin c3:='5'; c4:='3'; end;
if nmr=54 then begin c3:='5'; c4:='4'; end;
if nmr=55 then begin c3:='5'; c4:='5'; end;
if nmr=56 then begin c3:='5'; c4:='6'; end;
if nmr=57 then begin c3:='5'; c4:='7'; end;
if nmr=58 then begin c3:='5'; c4:='8'; end;
if nmr=59 then begin c3:='5'; c4:='9'; end;

if nmr=60 then begin c3:='6'; c4:='0'; end;
if nmr=61 then begin c3:='6'; c4:='1'; end;
if nmr=62 then begin c3:='6'; c4:='2'; end;
if nmr=63 then begin c3:='6'; c4:='3'; end;
if nmr=64 then begin c3:='6'; c4:='4'; end;
if nmr=65 then begin c3:='6'; c4:='5'; end;
if nmr=66 then begin c3:='6'; c4:='6'; end;
if nmr=67 then begin c3:='6'; c4:='7'; end;
if nmr=68 then begin c3:='6'; c4:='8'; end;
if nmr=69 then begin c3:='6'; c4:='9'; end;

if nmr=70 then begin c3:='7'; c4:='0'; end;
if nmr=71 then begin c3:='7'; c4:='1'; end;
if nmr=72 then begin c3:='7'; c4:='2'; end;
if nmr=73 then begin c3:='7'; c4:='3'; end;
if nmr=74 then begin c3:='7'; c4:='4'; end;
if nmr=75 then begin c3:='7'; c4:='5'; end;
if nmr=76 then begin c3:='7'; c4:='6'; end;
if nmr=77 then begin c3:='7'; c4:='7'; end;
if nmr=78 then begin c3:='7'; c4:='8'; end;
if nmr=79 then begin c3:='7'; c4:='9'; end;

if nmr=80 then begin c3:='8'; c4:='0'; end;
if nmr=81 then begin c3:='8'; c4:='1'; end;
if nmr=82 then begin c3:='8'; c4:='2'; end;
if nmr=83 then begin c3:='8'; c4:='3'; end;
if nmr=84 then begin c3:='8'; c4:='4'; end;
if nmr=85 then begin c3:='8'; c4:='5'; end;
if nmr=86 then begin c3:='8'; c4:='6'; end;
if nmr=87 then begin c3:='8'; c4:='7'; end;
if nmr=88 then begin c3:='8'; c4:='8'; end;
if nmr=89 then begin c3:='8'; c4:='9'; end;

if nmr=90 then begin c3:='9'; c4:='0'; end;
if nmr=91 then begin c3:='9'; c4:='1'; end;
if nmr=92 then begin c3:='9'; c4:='2'; end;
if nmr=93 then begin c3:='9'; c4:='3'; end;
if nmr=94 then begin c3:='9'; c4:='4'; end;
if nmr=95 then begin c3:='9'; c4:='5'; end;
if nmr=96 then begin c3:='9'; c4:='6'; end;
if nmr=97 then begin c3:='9'; c4:='7'; end;
if nmr=98 then begin c3:='9'; c4:='8'; end;
if nmr=99 then begin c3:='9'; c4:='9'; end;

if nmr>99 then
begin
showmessage('Nmr_in_c1c2c3c4: N>99 is unexpecetd...');
end; // nmr>9
end; // nmr_in_c1c2c3c4

procedure IntInChar(code:integer;var x:char; number:integer);
var maxnumber:integer;
begin

if code=0 then begin x:='0'; exit; end;

maxnumber:=number;
//if number>9 then maxnumber:=9;

if maxnumber>9 then x:='#';

if maxnumber=0 then x:='0';
if maxnumber=1 then x:='1';
if maxnumber=2 then x:='2';
if maxnumber=3 then x:='3';
if maxnumber=4 then x:='4';
if maxnumber=5 then x:='5';
if maxnumber=6 then x:='6';
if maxnumber=7 then x:='7';
if maxnumber=8 then x:='8';
if maxnumber=9 then x:='9';

if code=1 then x:='Y';

end; // intinchar

function encoder(x:integer):char;
var rez:char;
begin
rez:='0';
if x>=1 then rez:='1';
//if x>=2 then rez:='2';
//if x>=3 then rez:='3';
//if x>=4 then rez:='4';
encoder:=rez;
end; // encoder

function cri4(c1,c2,c3,c4:char):real;
var sum:real;
begin
sum:=0;
sum:=sum + ord(c1)*1000;
sum:=sum + ord(c2)*100;
sum:=sum + ord(c3)*10;
sum:=sum + ord(c4)*1;
cri4:=sum;
end; (* cri4 - in definition of the order of SA1 - SA2 - SA3 *)


function n_Cl(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms)-1 do
if (sms[k]='C') and (sms[k+1]='l') then inc(sum);
n_Cl:=sum;
end; // n_Cl

function n_Br(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms)-1 do
if (sms[k]='B') and (sms[k+1]='r') then inc(sum);
n_Br:=sum;
end; // n_Br

function n_F(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
if (sms[1]='F') then inc(sum);
for k:=1 to length(sms) do
//if (sms[k]='F') and not (sms[k+1] in ['e','r','m']) then inc(sum);
if (sms[k-1]<>'[') and (sms[k]='F') then inc(sum);
n_F:=sum;
end; // n_F

function n_I(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='I' then inc(sum);
n_I:=sum;
end; // n_I


function n_S(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
if (sms[1]='S') then inc(sum);
for k:=1 to length(sms) do
//if (sms[k]='S') and not (sms[k+1] in ['c','e','r','n','b','g','i']) then inc(sum);
if (sms[k-1]<>'[') and (sms[k]='S') then inc(sum);
n_S:=sum;
end; // n_S

function n_P(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
if (sms[1]='P') then inc(sum);
for k:=2 to length(sms) do
//if (sms[k]='P') and not (sms[k+1] in ['d','t','b','o','m','a','u']) then inc(sum);
if (sms[k-1]<>'[') and (sms[k]='P') then inc(sum);
n_P:=sum;
end; // n_P

function n_S2(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='s') and not (sms[k+1]=']') then inc(sum);
n_S2:=sum;
end; // n_S2

function n_O(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
if sms[1]='O' then inc(sum);
for k:=2 to length(sms) do
//if (sms[k]='O') and not (sms[k+1]='s') then inc(sum);
begin
if (sms[k-1]<>'[') and (sms[k]='O') then inc(sum);
if (sms[k]='O') and (sms[k+1]='-') then inc(sum);
end;
n_O:=sum;
end; // n_o

function n_Cupper(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
begin
if (sms[k]='C') and
   (sms[k+1]<>'l') and
   (sms[k+1]<>'a') and
   (sms[k+1]<>'s') and
   (sms[k+1]<>'o') and
   (sms[k+1]<>'u') and
   (sms[k+1]<>'d')
then inc(sum);
end;
n_Cupper:=sum;
end; // n_Cupper

function n_C_old(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
begin
if (sms[k]='C') then inc(sum);
end;
n_C_old:=sum;
end; // n_C_old

function n_Csp2(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='c' then inc(sum);
n_Csp2:=sum;
end; // n_Csp2

function n_dCC(var sms:string):integer;
begin
n_dCC:=( n_Csp2(sms)-n_Cupper(sms) );
end; // n_dCC

function n_dCCold(var sms:string):integer;
begin
n_dCCold:=( n_Csp2(sms)-n_C_old(sms) );
end; // n_dCCold


function n_N(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
if (sms[1]='N') then inc(sum);
for k:=2 to length(sms) do
//if (sms[k]='N') and not (sms[k+1] in ['e','i','b','p','o']) then inc(sum);
begin
if  (sms[k-1]<>'[') and (sms[k]='N') then inc(sum);
if  (sms[k]='N') and (sms[k+1]='+') then inc(sum);
end;
n_N:=sum;
end; // n_N

function n_N2(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='n' then inc(sum);
n_N2:=sum;
end; // n_N2

function n_1(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='-' then inc(sum);
n_1:=sum;
end; // n_line  = symbol '-' in SMILES

function n_2(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='=' then inc(sum);
n_2:=sum;
end; // n_line2 = symbol '=' in SMILES i.e., double bond

function n_3(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='#' then inc(sum);
n_3:=sum;
end; // n_line3 = symbol '#' in SMILES i.e., triple bons

function n_c1(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='1') then inc(sum);
n_c1:=sum;
end; // n_cyc = symbol '1' in SMILES i.e., cycles

function n_c2(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='2') then inc(sum);
n_c2:=sum;
end; // n_cyc = symbol '2' in SMILES i.e., cycles

function n_c3(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='3') then inc(sum);
n_c3:=sum;
end; // n_cyc = symbol '3' in SMILES i.e., cycles

function n_c4(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='4') then inc(sum);
n_c4:=sum;
end; // n_cyc = symbol '4' in SMILES i.e., cycles

function n_c5(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='5') then inc(sum);
n_c5:=sum;
end; // n_cyc = symbol '5' in SMILES i.e., cycles

function n_c6(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='6') then inc(sum);
n_c6:=sum;
end; // n_cyc = symbol '6' in SMILES i.e., cycles

function n_c7(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='7') then inc(sum);
n_c7:=sum;
end; // n_cyc = symbol '7' in SMILES i.e., cycles

function n_bk(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='(' then inc(sum);
n_bk:=sum;
end; // n_brackets

function n_bx(var sms:string; x:integer):integer;
var rez,k,sum:integer;
begin                            // if brackets 2 branch level=1
sum:=0;                          // if brackets 4 branch level=2
for k:=1 to length(sms) do       //             ...
if sms[k]='(' then inc(sum);     // if brackets 2x branch level=x
rez:=sum div 2;
if rez<>x then rez:=0 else rez:=1;
n_bx:=rez;
end; // n_bx

function n_CisTrans(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='/') or (sms[k]='\') then inc(sum);
n_CisTrans:=sum;
end; // n_CisTrans

function n_bk2(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if sms[k]='[' then inc(sum);
n_bk2:=sum;
end; // n_brackets2 [

function n_Rot(var sms:string):integer;
var k,sum:integer;
begin
sum:=0;
for k:=1 to length(sms) do
if (sms[k]='@') then inc(sum);
n_Rot:=sum;
end; // n_Rot

Procedure HALONOSP_YN
(
var
J_SF:integer;
nx, ny:integer;
CWS:CWsName
);
var
k:integer;
x,y:char;
begin

if (nx>0) and (ny>0) then
begin
inc(j_SF);

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:=CWs[k];

end; //

end; // HALONOSP_YN

Procedure HALONOSP_YN3
(
var
J_SF:integer;
nx, ny, nz:integer;
CWS:CWsName
);
label do_nothing;
var
k:integer;
x,y:char;
begin

if nx=0 then goto do_nothing;
if ny=0 then goto do_nothing;
if nz=0 then goto do_nothing;

// if (nx>0) and (ny>0) and (nz>0) then
begin
inc(j_SF);

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:=CWs[k];

end; //

do_nothing:

end; // HALONOSP_YN3

procedure filtr(var sms,smsfiltr:string);
var k:integer;                   memory:string;
begin

memory:=sms;

// [N+]
for k:=1 to length(sms)-4 do
if (sms[k  ]='[') and
   (sms[k+1]='N') and
   (sms[k+2]='+') and
   (sms[k+3]=']') then
   begin
    sms[k]:='N';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
   end;
// [H]
for k:=1 to length(sms)-3 do
if (sms[k  ]='[') and
   (sms[k+1]='H') and
   (sms[k+2]=']') then
   begin
    sms[k]:='*';
    sms[k+1]:='*';
    sms[k+2]:='*';
   end;



// [O-]
for k:=1 to length(sms)-4 do
if (sms[k  ]='[') and
   (sms[k+1]='O') and
   (sms[k+2]='-') and
   (sms[k+3]=']') then
   begin
    sms[k]:='O';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
   end;
// [C@H]
for k:=1 to length(sms)-5 do
if (sms[k  ]='[') and
   (sms[k+1]='C') and
   (sms[k+2]='@') and
   (sms[k+3]='H') and
   (sms[k+4]=']')

   then
   begin
    sms[k]:='C';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
    sms[k+4]:='*';
   end;
// [C@@H]
for k:=1 to length(sms)-6 do
if (sms[k  ]='[') and
   (sms[k+1]='C') and
   (sms[k+2]='@') and
   (sms[k+3]='@') and
   (sms[k+4]='H') and
   (sms[k+5]=']')

   then
   begin
    sms[k]:='C';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
    sms[k+4]:='*';
    sms[k+5]:='*';
   end;

// [Na+]
for k:=1 to length(sms)-5 do
if (sms[k  ]='[') and
   (sms[k+1]='N') and
   (sms[k+2]='a') and
   (sms[k+3]='+') and
   (sms[k+4]=']')
   then
   begin
    sms[k]:='N';
    sms[k+1]:='a';
    sms[k+2]:='*';
    sms[k+3]:='*';
    sms[k+4]:='*';
   end;

// [NH4+]
for k:=1 to length(sms)-6 do
if (sms[k  ]='[') and
   (sms[k+1]='N') and
   (sms[k+2]='H') and
   (sms[k+3]='4') and
   (sms[k+4]='+') and
   (sms[k+5]=']')
   then
   begin
    sms[k]:='N';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
    sms[k+4]:='*';
    sms[k+5]:='*';
   end;
// [K+]
for k:=1 to length(sms)-4 do
if (sms[k  ]='[') and
   (sms[k+1]='K') and
   (sms[k+2]='+') and
   (sms[k+3]=']') then
   begin
    sms[k]:='K';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
   end;
// [S-]
for k:=1 to length(sms)-4 do
if (sms[k  ]='[') and
   (sms[k+1]='S') and
   (sms[k+2]='-') and
   (sms[k+3]=']') then
   begin
    sms[k]:='S';
    sms[k+1]:='*';
    sms[k+2]:='*';
    sms[k+3]:='*';
   end;


for k:=1 to length(sms) do if sms[k]='.' then sms[k]:='*';
for k:=1 to length(sms) do if ( sms[k]='[') or (sms[k]=']') then sms[k]:='*';

////////////////////////////////////////////////////////

   smsfiltr:='';
   for k:=1 to length(sms)-1 do
   if sms[k]<>'*' then
    begin
     smsfiltr:=smsfiltr + sms[k];
    end;

    sms:=memory;

end; // filtr

function ec0multigraph(var adj:adjacency; var n:integer; k:integer):integer;
var j,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[k,j]<>0 then sum:=sum+adj[k,j];
ec0multigraph:=sum;
end; // ec0;

function ec0(var adj:adjacency; var n:integer; k:integer):integer;
var j,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[k,j]<>0 then inc(sum);
ec0:=sum;
end; // ec0;

function pt2(var adj:adjacency; var n:integer; k:integer):integer;
var j,L,sum:integer;
begin
sum:=0;
for j:=1 to n do
 if adj[k,j]<>0 then
  for L:=1 to n do
   if (adj[L,j]<>0) and (l<>k) then inc(sum);
pt2:=sum;
end; // pt2

function pt3(var adj:adjacency; var n:integer; kk:integer):integer;
var j,k,L,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[kk,j]<>0 then         // kk-j
for k:=1 to n do
if (adj[k,j]<>0) and (k<>kk) then   // kk-j-k
for L:=1 to n do
if (adj[k,L]<>0) and (kk<>L) and (j<>L) then inc(sum);    // kk-j-k-L
pt3:=sum;
end; // pt3

// june 8, 2018
function pt4(var adj:adjacency; var n:integer; kk:integer):integer;
var j,k,L,m,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[kk,j]<>0 then         // kk-j
for k:=1 to n do
if (adj[k,j]<>0) and (k<>kk) then   // kk-j-k
for L:=1 to n do
if (adj[k,L]<>0) and (kk<>L) and (j<>L) then
for m:=1 to n do
if (adj[k,m]<>0) and (kk<>L) and (j<>L) and (l<>m) then inc(sum);    // kk-j-k-L-m
pt4:=sum;
end; // pt4



function s2(var adj:adjacency; var n:integer; kk:integer):integer;
var j,k,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[kk,j]<>0 then
for k:=1 to n do
if (adj[k,j]<>0) and (kk<>k) then sum:=sum + ec0(adj,n,k);
s2:=sum;
end; // s2


function s3(var adj:adjacency; var n:integer; kk:integer):integer;
var j,k,L,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[kk,j]<>0 then         // kk-j
for k:=1 to n do
if (adj[k,j]<>0) and (k<>kk) then   // kk-j-k
for L:=1 to n do
if (adj[k,L]<>0) and (kk<>L) and (j<>L) then sum:=sum+ec0(adj,n,L); // kk-j-k-L
s3:=sum;
end; // s3

function AtomNumber(var x:atomic_name):integer;
var rez:integer;
begin

rez:=0;

if                (x[1]='H') then rez:= 1;
if                (x[1]='B') then rez:= 5;


if ((x[1]='C')  or (x[1]='c')) and (x[2]<>'l') then rez:= 6;
(**)
if (x[1]='N')  or (x[1]='n') then rez:= 7;
if (x[1]='O')  or (x[1]='o') then rez:= 8;

if                (x[1]='F') then rez:= 9;

if (x[1]='N') and (x[2]='a') then rez:=11;
if (x[1]='A') and (x[2]='l') then rez:=13;

if                (x[1]='P') then rez:=15;
if (x[1]='S')  or (x[1]='s') then rez:=16;

if                (x[1]='K') then rez:=19;

if (x[1]='C') and (x[2]='l') then rez:=17;

if (x[1]='G') and (x[2]='a') then rez:=31;
if (x[1]='G') and (x[2]='e') then rez:=32;
if (x[1]='A') and (x[2]='s') then rez:=33;


if (x[1]='B') and (x[2]='r') then rez:=35;
if (x[1]='T') and (x[2]='e') then rez:=52;

if                (x[1]='I') then rez:=53;

(* July 22, 2022 a problem...
if rez=0 then
begin
showmessage('GAO problems '+x);
end; // rez=0
*)

AtomNumber:=rez;

end; // AtomNumber


// ggg
function Carbon2p2(var atao:atomic_name):boolean;
label outof;
var rez:boolean;
begin
rez:=False;
//if (atao[1]='C') and (atao[2]=' ') then

if AtomNumber(atao)=6 then
  begin
  rez:=true;
  goto outof;
  end; // C

if (atao[1]='2') and (atao[2]='p') and (atao[3]='2') then rez:=true;
outof:
Carbon2p2:=rez;
end; // carbon2p2

function nnc(var adj:adjacency; var n:integer; var k:integer):integer;
var Nall, Ncarbon, Nnoncarbon,j, sum:integer;

begin

Nall:=0;
Ncarbon:=0;
Nnoncarbon:=0;
for j:=1 to n do
 begin
  if adj[j,k]<>0 then
  begin
   inc(Nall);
   if Carbon2p2(listofatom[j]) then inc(Ncarbon)
                               else inc(Nnoncarbon);
  end; // adjk,kk<>0
 end; // k
nnc:=100*Nall + 10*Ncarbon + Nnoncarbon;
end; // nnc

function ec1(var adj:adjacency; var n:integer; k:integer):integer;
var j,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[k,j]<>0 then sum:=sum + ec0(adj,n,j);
ec1:=sum;
end; // ec0;

function ec2(var adj:adjacency; var n:integer; k:integer):integer;
var j,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[k,j]<>0 then sum:=sum + ec1(adj,n,j);
ec2:=sum;
end; // ec0;

function ec3(var adj:adjacency; var n:integer; k:integer):integer;
var j,sum:integer;
begin
sum:=0;
for j:=1 to n do
if adj[k,j]<>0 then sum:=sum + ec2(adj,n,j);
ec3:=sum;
end; // ec0;

function do_ecX(
var adj:adjacency;
var n:integer;
k:integer; // number of vertex
x:integer  // order of the morgan extended connectivity 0,1,2,3; pt2, pt3, Shells2
):integer;
var rez:integer;
    txt:string;
    r:integer;
begin
if x=0 then rez:=ec0(adj,n,k);          // ec0
if x=1 then rez:=ec1(adj,n,k);          // ec1
if x=2 then rez:=ec2(adj,n,k);          // ec2
if x=3 then rez:=ec3(adj,n,k);          // ec3

if x=4 then rez:=pt2(adj,n,k);          // pt2
if x=5 then rez:=pt3(adj,n,k);          // pt3

if x=9 then rez:=pt4(adj,n,k);          // pt4      june 8, 2018

if x=6 then rez:=S2 (adj,n,k);          // sv2
if x=7 then rez:=S3 (adj,n,k);          // sv3      june 8, 2018

if x=8 then rez:=nnc(adj,n,k);          // NNC


if rez>9999 then
begin
txt:='Function ECX: InvariantValue>9999 (it is '+inttostr(rez)+') STOP process [y]';
r:=messageDlg(txt,mtConfirmation,[mbYes,mbNo,mbCancel],0);
if r=mrYes then halt;

end; // rez > 9999

do_ecx:=rez;
end; // ecX


(**)
function cyc7(var adj:adjacency;var aroma,heter:char;var n:integer):integer;
label out;
var sum,k1,k2,k3,k4,k5,k6,k7,k8:integer;
begin

aroma:='.';         // aromaticity or not ordinary bonds
heter:='.';         // presence of heteroatoms

sum:=0;
for k1:=1 to n-1 do
for k2:=1+k1 to n do
if adj[k1][k2]<>0 then
for k3:=1 to n do
if k1<>k3 then
if k2<>k3 then
if (adj[k2][k3]<>0) and (k3<>k1) then
for k4:=1 to n do
if k1<>k4 then
if k2<>k4 then
if k3<>k4 then
if (adj[k3][k4]<>0) and (k4<>k2) then
for k5:=1 to n do
if k1<>k5 then
if k2<>k5 then
if k3<>k5 then
if k4<>k5 then
if (adj[k4][k5]<>0) and (k5<>k3) then
for k6:=1 to n do
if k1<>k6 then
if k2<>k6 then
if k3<>k6 then
if k4<>k6 then
if k5<>k6 then
if (adj[k5][k6]<>0) and (k6<>k4) then
for k7:=1 to n do
if k1<>k7 then
if k2<>k7 then
if k3<>k7 then
if k4<>k7 then
if k5<>k7 then
if k6<>k7 then
if (adj[k6][k7]<>0) and (k7<>k5) then
for k8:=1 to n do
if k2<>k8 then
if k3<>k8 then
if k4<>k8 then
if k5<>k8 then
if k6<>k8 then
if k7<>k8 then
if (adj[k7][k8]<>0) and (k8=k1) then
begin
sum:=sum+1;

if not form1.checkbox31.Checked then
begin
 if aroma='.' then if ListOfAtom[k1][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k2][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k3][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k4][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k5][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k6][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k7][1]='c' then aroma:='A';

 if heter='.' then if (ListOfAtom[k1][1]<>'c') and (ListOfAtom[k1][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k2][1]<>'c') and (ListOfAtom[k2][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k3][1]<>'c') and (ListOfAtom[k3][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k4][1]<>'c') and (ListOfAtom[k4][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k5][1]<>'c') and (ListOfAtom[k5][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k6][1]<>'c') and (ListOfAtom[k6][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k7][1]<>'c') and (ListOfAtom[k7][1]<>'C') then heter:='H';

end; // not checkbox31 = GAO
end;
//out:
cyc7:=sum div 7;
end; (*c7*)

function cyc6(var adj:adjacency;var aroma,heter:char;var n:integer):integer;
label out;
var sum,k1,k2,k3,k4,k5,k6,k7:integer;
begin

aroma:='.';         // aromaticity
heter:='.';         // presence of heteroatoms

sum:=0;
for k1:=1 to n-1 do
for k2:=1+k1 to n do
if adj[k1][k2]<>0 then
for k3:=1 to n do
if k1<>k3 then
if k2<>k3 then
if (adj[k2][k3]<>0) and (k3<>k1) then
for k4:=1 to n do
if k1<>k4 then
if k2<>k4 then
if k3<>k4 then
if (adj[k3][k4]<>0) and (k4<>k2) then
for k5:=1 to n do
if k1<>k5 then
if k2<>k5 then
if k3<>k5 then
if k4<>k5 then
if (adj[k4][k5]<>0) and (k5<>k3) then
for k6:=1 to n do
if k1<>k6 then
if k2<>k6 then
if k3<>k6 then
if k4<>k6 then
if k5<>k6 then
if (adj[k5][k6]<>0) and (k6<>k4) then
for k7:=1 to n do
if k2<>k7 then
if k3<>k7 then
if k4<>k7 then
if k5<>k7 then
if k6<>k7 then
if (adj[k6][k7]<>0) and (k7=k1) then
begin
sum:=sum+1;

if not form1.checkbox31.Checked then
begin
 if aroma='.' then if ListOfAtom[k1][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k2][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k3][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k4][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k5][1]='c' then aroma:='A';
 if aroma='.' then if ListOfAtom[k6][1]='c' then aroma:='A';

 if heter='.' then if (ListOfAtom[k1][1]<>'c') and (ListOfAtom[k1][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k2][1]<>'c') and (ListOfAtom[k2][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k3][1]<>'c') and (ListOfAtom[k3][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k4][1]<>'c') and (ListOfAtom[k4][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k5][1]<>'c') and (ListOfAtom[k5][1]<>'C') then heter:='H';
 if heter='.' then if (ListOfAtom[k6][1]<>'c') and (ListOfAtom[k6][1]<>'C') then heter:='H';
end; // checkbox31 = GAO
end;
//out:
cyc6:=sum div 6;
end; (*c6*)

function cyc5(var adj:adjacency;var aroma,heter:char;var n:integer):integer;
label out;
var sum,k1,k2,k3,k4,k5,k6:integer;
begin

aroma:='.';         // aromaticity
heter:='.';         // presence of heteroatoms

sum:=0;
for k1:=1 to n-1 do
for k2:=1+k1 to n do
if adj[k1][k2]<>0 then
for k3:=1 to n do
if k1<>k3 then
if k2<>k3 then
if (adj[k2][k3]<>0) and (k3<>k1) then
for k4:=1 to n do
if k1<>k4 then
if k2<>k4 then
if k3<>k4 then
if (adj[k3][k4]<>0) and (k4<>k2) then
for k5:=1 to n do
if k1<>k5 then
if k2<>k5 then
if k3<>k5 then
if k4<>k5 then
if (adj[k4][k5]<>0) and (k5<>k3) then
for k6:=1 to n do
//if k1<>k6 then
if k2<>k6 then
if k3<>k6 then
if k4<>k6 then
if k5<>k6 then
if (adj[k5][k6]<>0) and (k6=k1) then
begin
sum:=sum+1;

if not form1.checkbox31.Checked then
begin
if aroma='.' then if ListOfAtom[k1][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k2][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k3][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k4][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k5][1]='c' then aroma:='A';

if heter='.' then if (ListOfAtom[k1][1]<>'c') and (ListOfAtom[k1][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k2][1]<>'c') and (ListOfAtom[k2][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k3][1]<>'c') and (ListOfAtom[k3][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k4][1]<>'c') and (ListOfAtom[k4][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k5][1]<>'c') and (ListOfAtom[k5][1]<>'C') then heter:='H';
end; // checkbox31 = GAO
end;
//out:
cyc5:=sum div 5;
end; (*c5*)

function cyc4(var adj:adjacency;var aroma,heter:char;var n:integer):integer;
label out;
var sum,k1,k2,k3,k4,k5:integer;
begin

aroma:='.';         // aromaticity
heter:='.';         // presence of heteroatoms

sum:=0;
for k1:=1 to n-1 do
for k2:=1+k1 to n do
if adj[k1][k2]<>0 then
for k3:=1 to n do
if k1<>k3 then
if k2<>k3 then
if (adj[k2][k3]<>0) and (k3<>k1) then
for k4:=1 to n do
if k1<>k4 then
if k2<>k4 then
if k3<>k4 then
if (adj[k3][k4]<>0) and (k4<>k2) then
for k5:=1 to n do
if k2<>k5 then
if k3<>k5 then
if k4<>k5 then
if (adj[k4][k5]<>0) and (k5=k1) then
begin
sum:=sum+1;


if not form1.checkbox31.Checked then
begin
if aroma='.' then if ListOfAtom[k1][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k2][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k3][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k4][1]='c' then aroma:='A';

if heter='.' then if (ListOfAtom[k1][1]<>'c') and (ListOfAtom[k1][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k2][1]<>'c') and (ListOfAtom[k2][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k3][1]<>'c') and (ListOfAtom[k3][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k4][1]<>'c') and (ListOfAtom[k4][1]<>'C') then heter:='H';
end; // checkbox31 = GAO
end;
//out:
cyc4:=sum div 4;
end; (*c5*)

function cyc3(var adj:adjacency;var aroma,heter:char;var n:integer):integer;
label out;
var sum,k1,k2,k3,k4,k5:integer;
begin

aroma:='.';         // aromaticity
heter:='.';         // presence of heteroatoms

sum:=0;
for k1:=1 to n-1 do
for k2:=1+k1 to n do
if adj[k1][k2]<>0 then
for k3:=1 to n do
if k2<>k3 then
if (adj[k2][k3]<>0) and (k3<>k1) then
for k4:=1 to n do
if k3<>k4 then
if (adj[k3][k4]<>0) and (k4=k1) then
begin
sum:=sum+1;

if not form1.checkbox31.Checked then
begin
if aroma='.' then if ListOfAtom[k1][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k2][1]='c' then aroma:='A';
if aroma='.' then if ListOfAtom[k3][1]='c' then aroma:='A';

if heter='.' then if (ListOfAtom[k1][1]<>'c') and (ListOfAtom[k1][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k2][1]<>'c') and (ListOfAtom[k2][1]<>'C') then heter:='H';
if heter='.' then if (ListOfAtom[k3][1]<>'c') and (ListOfAtom[k3][1]<>'C') then heter:='H';
end; // Checkbox31 = GAO
end;
//out:
cyc3:=sum div 3;
end; (*c5*)



procedure insertSF(a,b,c:str4; id:integer);

begin
local_SF_list[id]:='';

repeat if length(a)<4 then a:=a+'.'; until length(a)>=4;
repeat if length(b)<4 then b:=b+'.'; until length(b)>=4;
repeat if length(c)<4 then c:=c+'.'; until length(c)>=4;

if b[1]='c' then b[1]:='C';
if b[1]='n' then b[1]:='N';


local_SF_list[id]:=a+b+c;
end; // insert a,b,c SF

procedure insertSF_HI(a,b,c:str4; id:integer);

begin
HI_SF_list[id]:='';

repeat if length(a)<4 then a:=a+'.'; until length(a)>=4;
repeat if length(b)<4 then b:=b+'.'; until length(b)>=4;
repeat if length(c)<4 then c:=c+'.'; until length(c)>=4;

if b[1]='c' then b[1]:='C';
if b[1]='n' then b[1]:='N';

HI_SF_list[id]:=a+b+c;
end; // insert a,b,c SF

procedure load_AOs; // load of the atomic orbitals
label outof;
var o,       // file output
    f:text;  // File AOs.txt
    i,j,k:integer; 
    mes, // for message
    s:string;
    ch:char;
    port:array[1..5] of char;
begin

assign(f,'AOs.txt');
reset(f);

readln(f);
readln(f);
readln(f);
readln(f);

for i:=1 to MaxAtomNumber do
begin
j:=0;
repeat inc(j);

if j>MaxAtomNumber then
showmessage('Number of Chemical element is too large '+inttostr(j));

for k:=1 to 5 do read(f,port[k]);
// showmessage(port);
for k:=1 to 4 do AO[i][j][k]:=port[k];
until port[5]=';';
Nao[i]:=j;
readln(f);
end; // i: maxnao

close(f);

(*
showmessage('Load AOS is completed');

assign(f,'AOsLoad.txt');
rewrite(f);
for i:=1 to MaxAtomNumber do
begin
write(f,i:3,'  ');
for j:=1 to Nao[i] do
begin
for k:=1 to 4 do write(f,ao[i][j][k]); write(f,' ');
end;
writeln(f);
end; // i

close(f);
*)
end; // load Atomic orbitals


procedure HFG_in_GAO                      //
(var adj,adj2:adjacency;
var listOfAtom:ChemicalElements;
var ListOfAO:ChemicalElements;
var N_HFG:integer;
var N_GAO:integer
);

var
    AtNum,
    k,j,kk,jj,basa:integer;
    f:text;
    x:string; // April 3,2023 this for extract 1s1 1s2 2s2 ... 3d10
begin

load_AOs; // download data on atomic orbitals such as 1s1, 2s2, .. 3d10..

for k:=1 to maxsize do
for j:=1 to maxsize do adj2[k][j]:=-1;

basa:=0;

for k:=1 to N_HFG do
begin
AtNum:=AtomNumber(ListOfAtom[k]);
if AtNum=0 then showmessage('HFG_in_GAO:Atom is not available '+ListOfAtom[k]);
// showmessage(ListOfAtom[k]+' '+inttostr(Nao[atNum])+' BASA='+inttostr(basa));
for j:=basa+1 to basa + Nao[AtNum] do adj2[j,j]:=k;

for j:=basa+1 to basa + Nao[AtNum] do

begin
//x:='';

listofAO[j]:='';
for jj:=1 to 4 do listofAO[j]:=listofAO[j]+AO[AtNum][j-basa][jj];

//for jj:=1 to 4 do listOfAO[j][jj]:=AO[AtNum][j-basa][jj];
//listofAO[j]:=x;
//showmessage(IntToStr(j)+' '+x+' '+listofAO[j]);
end; // j

basa:=basa + Nao[AtNum];
end; // k; i.e., k is placed in diagonal of the GAO adjacency

N_GAO:=basa;

if N_GAO>maxsize then
begin
showmessage('NGAO='+inttostr(N_GAO)+' MaxSize='+IntToStr(MaxSize)+' Task is unsoluble');
Halt;
end; //

for k:=1 to N_HFG do
for j:=1 to N_HFG do
begin
 if adj[k,j]<>0 then
 begin
   for kk:=1 to N_GAO do
   for jj:=1 to N_GAO do
   if (adj2[kk,kk]=k) and (adj2[jj,jj]=j) then
   begin
   adj2[kk,jj]:=1;
   adj2[jj,kk]:=1;
   end; // kk,jj
 end; // adj[k,j]<>0
end; // k,j

for kk:=1 to N_GAO do                  // zero in all elements which are not
for jj:=1 to N_GAO do                  // a[kk,jj]=1
if adj2[kk,jj]<0 then adj2[kk,jj]:=0;

for kk:=1 to N_GAO do adj2[kk,kk]:=0;  // zero in all elements of diagonal


adj:=adj2;
n_HFG:=n_GAO;
for k:=1 to n_HFG do
begin
ListOfAtom[k]:='';
for j:=1 to 4 do
listOfAtom[k]:=listOfAtom[k]+ListOfAO[k][j];
end; // k


(*
assign(f,'adjGAO.txt');
rewrite(f);

for k:=1 to N_GAO do
begin
for jj:=1 to 4 do write(f,ListOfAO[k][jj]);
write(f,':');
for j:=1 to N_GAO do write(f,adj2[k,j]:3); writeln(f,ec0(adj2,n_gao,k):4);
end; // k

close(f);
showmessage('See adjGAO.txt');
*)

end; // HFG in GAO

procedure HSG_in_HFG(
var adj,adj2:adjacency;
var listOfAtom:ChemicalElements;
var n:integer);

var k,j,
    VD   // vertex degree
    :integer;
//    f:textfile;
begin

(*
assign(f,'#HSGinHFG.txt'); rewrite(f);
for k:=1 to n do
begin
for j:=1 to length(listofatom[k]) do write(f,listOfAtom[k]);
writeln(f);
end; // k
closefile(f);
*)
for k:=1 to n do
if (
   (listOfAtom[k,1]='C') or
   (listOfAtom[k,1]='c') or
   (listOfAtom[k,1]='N') or
   (listOfAtom[k,1]='o') or
   (listOfAtom[k,1]='n') or
   (listOfAtom[k,1]='O')
   )
then
begin

 if (listOfAtom[k,1]='C') then
  begin
   VD:=ec0multigraph(adj,n,k);
   for J:=1 to 4-VD do
    begin
     inc(n);
     adj[k,n]:=1;
     adj[n,k]:=1;
     ListOfAtom[n]:='H';
    end; // J
  end; // C
(*
  if (listOfAtom[k,1]='S') and (ListOfAtom[k,2]='i') then
  begin
   VD:=ec0multigraph(adj,n,k);
   for J:=1 to 4-VD do
    begin
     inc(n);
     adj[k,n]:=1;
     adj[n,k]:=1;
     ListOfAtom[n]:='H';
    end; // J
  end; // C
*)


if listOfAtom[k,1]='c' then
  begin
   VD:=ec0multigraph(adj,n,k);
   for J:=1 to 3-VD do
    begin
     inc(n);
     adj[k,n]:=1;
     adj[n,k]:=1;
     ListOfAtom[n]:='H';
    end; // J
  end; // c

 if (listOfAtom[k,1]='N') then
  begin
   VD:=ec0multigraph(adj,n,k);
   for J:=1 to 3-VD do
    begin
     inc(n);
     adj[k,n]:=1;
     adj[n,k]:=1;
     ListOfAtom[n]:='H';
    end; // J
  end; // N

 if listOfAtom[k,1]='n' then
  begin
   VD:=ec0multigraph(adj,n,k);
   for J:=1 to 2-VD do
    begin
     inc(n);
     adj[k,n]:=1;
     adj[n,k]:=1;
     ListOfAtom[n]:='H';
    end; // J
  end; // n

 if (listOfAtom[k,1]='O') or
    (listOfAtom[k,1]='o') or
    (listOfAtom[k,1]='S') or
    (listOfAtom[k,1]='s')
 then
  begin
   VD:=ec0multigraph(adj,n,k);
   for J:=1 to 2-VD do
    begin
     inc(n);
     adj[k,n]:=1;
     adj[n,k]:=1;
     ListOfAtom[n]:='H';
    end; // J
  end; // n


end; // k

for k:=1 to n do
begin
if ListOfAtom[k,1]='c' then ListOfAtom[k,1]:='C';
if ListOfAtom[k,1]='n' then ListOfAtom[k,1]:='N';
if ListOfAtom[k,1]='s' then ListOfAtom[k,1]:='S';
if ListOfAtom[k,1]='o' then ListOfAtom[k,1]:='O';
end;


end; //HSG in HFG

(*
// ggg
function HyperIndex(var adj:adjacency; var n_loc:integer; LIcode:integer):char;
var k,
    kk,
    eqpos,
    max,
    j_inv
    :integer;
    atom4,degr4:string[4];
    per
    :real;
    rez:char;
    f:textfile;
begin

hypercode:=StrToInt(form1.Edit26.Text);

j_inv:=0;

for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,HyperCode) );
atom4:=ListOfAtom[k];
insertSF_HI('Hyp-',atom4,degr4,j_inv);
end; // k

//assign(f,'#Hi.txt'); rewrite(f);
//for k:=1 to n_loc do writeln(f,HI_SF_list[k]); writeln(f,n_loc);
//closefile(f);

max:=0;
for k:=1 to n_loc do
begin
eqpos:=0;
for kk:=1 to n_loc do
if CWsNameSame(HI_SF_list[k],HI_SF_list[kk]) then inc(eqpos);
if max<eqpos then max:=eqpos;
end; // k

per:=eqpos/n_loc;

if per>0.0 then rez:='A';
if per>0.1 then rez:='B';
if per>0.2 then rez:='C';
if per>0.3 then rez:='D';
if per>0.4 then rez:='E';
if per>0.5 then rez:='F';
if per>0.6 then rez:='G';
if per>0.7 then rez:='H';
if per>0.8 then rez:='I';
if per>0.9 then rez:='J';

//showmessage('HyperIndex: '+rez+'   max='+inttostr(max)+'  n='+inttostr(n_loc));

HyperIndex:=rez;
end; //(HI)
*)
// gg
                                      // June 21, 2018
function noabs(x:integer):integer;    // it is not claer who better LI1-LI2 or abs(LI1-LI2) ?
begin                                 // from politics point of view ABS is preferable...
noabs:=abs(x);
end; // no abs

procedure do_aaChaos(var smsi:string;var CWS:CWsName; var nenuzhen:integer);
var k,j:integer;
    sms,
    z:string;
    leng,
    sum,
    max,
    chaos:integer;
begin

leng:=length(smsi);
max:=-1;
for k:=1 to leng do
  begin
  sum:=0;
    for j:=1 to leng do
    if smsi[k]=smsi[j] then sum:=sum+1;
    if sum>max then max:=sum;
  end; // k

chaos := round( 10* (1 - max /leng) );

     if chaos<100 then z:=IntToStr(chaos)
                  else z:='*';

     CWS:='';
     CWS:=CWS+'[AA'+z+']';
//     tester6:=CWS;
     repeat CWS:=CWS +'.'; until length(CWs)>=12;


end; // do:aachaos i.e. chaos in sequence of amino acids (peptide)


procedure do_chaos(var smsi:string; var CWS:CWsName;var nadj:integer);
var k,j:integer;
    sms,
    z:string;
    sum,
    max,
    chaos:integer;
begin
//  March30,2023
//  Chaos = round [  [ Nmax  / Nall ] * 100 ]

// tester6:='';

max:=-1;
for k:=1 to nadj do
   begin
      sum:=0;
      for j:=1 to nadj do if listOfAtom[j]=listOfAtom[k] then sum:=sum+1;

        if sum>max then
          begin
          max:=sum;
          end; //  sum > max
   end; // k

chaos := round( 10* (1 - max /nadj) );

     if chaos<100 then z:=IntToStr(chaos)
                  else z:='*';

     CWS:='';
     CWS:=CWS+'[chaos'+z+']';
     tester6:=CWS;
     repeat CWS:=CWS +'.'; until length(CWs)>=12;

end; // Do_chaos


procedure do_mg_invariants
(
var sms:string;
var cas:string;
var Local_SF_list:SFlist;
var N_loc:integer
);

var
    j_inv,   // number of an invariant
    x1,x2,   // numerical values of a couple of invariants June 20, 2018
    rr,      // the number of cycles rings in molecule March 18, 2020
    k,j,sum:integer;
    atom4,degr4:string[4];
    smsFiltr:string;
    aroma,     // if aromaticity in cycle aroma=A
    heter:char;// if heteroatoms in cycle heter=H
    Nadj:integer;
    f:text;
    HI:char;

begin

filtr(sms,smsfiltr); // [N+] = N;  [O-] = O     etc.

SMILES_in_Adj(smsfiltr,adj,N_HSG,ListOfAtom);

         // ...29 = HFG                   ...31 = GAO

(*
assign(f,'!see.txt');
rewrite(f);
for k:=1 to n_HSG do
begin
for j:=1 to length(listofatom[k]) do write(f,listofatom[k,j]);
writeln(f,';');
end; // k
closefile(f);

showmessage('See !see.txt');
*)

n_loc:=N_HSG;

if (form1.CheckBox29.Checked) or (form1.CheckBox31.Checked) then
begin
N_HFG:=N_HSG;
HSG_in_HFG(Adj,Adj2,ListOfAtom,N_HFG);
n_loc:=N_HFG;
end; // HSG -> HFG

if form1.CheckBox31.Checked then
HFG_in_GAO(adj,adj2,ListOfAtom,ListOfAO,n_loc,n_GAO);


j_inv:=0;

if form1.CheckBox9.Checked then // 0 EC0
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,0) );
atom4:=ListOfAtom[k];
insertSF('EC0-',atom4,degr4,j_inv);
end; // 22

if form1.CheckBox28.Checked then // 1 EC1
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,1) );
atom4:=ListOfAtom[k];
insertSF('EC1-',atom4,degr4,j_inv);
end; // 23

if form1.CheckBox18.Checked then // 2 EC2
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,2) );
atom4:=ListOfAtom[k];
insertSF('EC2-',atom4,degr4,j_inv);
end; // 25

(**)
if form1.CheckBox10.Checked then // 3 EC3 renoved June 8, 2018
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,3) );
atom4:=ListOfAtom[k];
insertSF('EC3-',atom4,degr4,j_inv);
end; // 27
(**)
if form1.CheckBox6.Checked then // 4 PT2
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,4) );
atom4:=ListOfAtom[k];
insertSF('PT2-',atom4,degr4,j_inv);
end; // checkbox1

if form1.CheckBox12.Checked then // 5 PT3
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,5) );
atom4:=ListOfAtom[k];
insertSF('PT3-',atom4,degr4,j_inv);
end; // checkbox1

if form1.CheckBox36.Checked then // 5 PT4 June 8, 2018
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,9) );
atom4:=ListOfAtom[k];
insertSF('PT4-',atom4,degr4,j_inv);
end; // checkbox1

if form1.CheckBox13.Checked then // 6 VS2
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,6) );
atom4:=ListOfAtom[k];
insertSF('VS2-',atom4,degr4,j_inv);
end; // checkbox1

(**)
if form1.CheckBox37.Checked then // 7 VS3   jun 8, 2018
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,7) );
atom4:=ListOfAtom[k];
insertSF('VS3-',atom4,degr4,j_inv);
end; // checkbox1
(**)

if form1.CheckBox20.Checked then // 8 NNC
for k:=1 to n_loc do
begin
inc(j_inv);
degr4:=inttostr( do_ecx(adj,n_loc,k,8) );
atom4:=ListOfAtom[k];
insertSF('NNC-',atom4,degr4,j_inv);
end; // checkbox1

// global graph invariants
(**)
if form1.CheckBox4.Checked then     //
begin
rr:=cyc7(adj,aroma,heter,n_loc);
if rr>0 then
begin
  inc(j_inv);
  degr4:=inttostr(rr);
  atom4:='.'+aroma+heter+'.';
  insertSF('C7..',atom4,degr4,j_inv);
end; // rr>0
end; // checkBox4 = C7

if form1.CheckBox19.Checked then     // C6 cycle ring 6
begin
rr:=cyc6(adj,aroma,heter,n_loc);
if rr>0 then
begin
inc(j_inv);
degr4:=inttostr(rr);
atom4:='.'+aroma+heter+'.';
insertSF('C6..',atom4,degr4,j_inv);
end; // rr>0
end; // checkBox19 = C6

if form1.CheckBox16.Checked then
begin
rr:=cyc5(adj,aroma,heter,n_loc);
if rr>0 then
begin
inc(j_inv);
degr4:=inttostr(rr);
atom4:='.'+aroma+heter+'.';
insertSF('C5..',atom4,degr4,j_inv);
end; // rr>0
end; // checkbox16  = C5

if form1.CheckBox8.Checked then
begin

rr:=cyc4(adj,aroma,heter,n_loc);
if rr>0 then
begin
inc(j_inv);
degr4:=inttostr(rr);
atom4:='.'+aroma+heter+'.';
insertSF('C4..',atom4,degr4,j_inv);
end; // rr > 0
end; // checkbox8  = C4

if form1.CheckBox5.Checked then
begin
rr:=cyc3(adj,aroma,heter,n_loc);
if rr>0 then
begin
inc(j_inv);
degr4:=inttostr(rr);
atom4:='.'+aroma+heter+'.';
insertSF('C3..',atom4,degr4,j_inv);
end; // rr > 0
end; // checkbox5  = C3

////////////////////////////////////////////////////////
// Super Quadrat START                                //
// ============ June 20, 2018 copules of LI1 + LI2    //
////////////////////////////////////////////////////////


if form1.CheckBox132.Checked then
begin
inc(j_inv);
do_chaos(sms,local_SF_list[j_inv],n_loc); // preparation of the SAk = [chaosN]........
zzz:=zzz + tester6;
end; // do xyyx

// block ec0 start
if form1.CheckBox69.Checked then // e0 + e1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0e1',atom4,degr4,j_inv);
end; // checkbox69

if form1.CheckBox79.Checked then // e0 +e2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0e2',atom4,degr4,j_inv);
end; // checkbox79

if form1.CheckBox89.Checked then // e0 +e3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0e3',atom4,degr4,j_inv);
end; // checkbox89

if form1.CheckBox99.Checked then // e0 +p2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0p2',atom4,degr4,j_inv);
end; // checkbox99

if form1.CheckBox109.Checked then // e0 +p3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0p3',atom4,degr4,j_inv);
end; // checkbox109

if form1.CheckBox119.Checked then // e0 +p4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0p4',atom4,degr4,j_inv);
end; // checkbox129

if form1.CheckBox129.Checked then // e0 +s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0s2',atom4,degr4,j_inv);
end; // checkbox129

if form1.CheckBox49.Checked then // e0 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0s3',atom4,degr4,j_inv);
end; // checkbox49

if form1.CheckBox39.Checked then // e0 +nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,0);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e0nn',atom4,degr4,j_inv);
end; // checkbox39

// block ec0 end

// ******************************* block ec1 start

if form1.CheckBox65.Checked then // E1 - E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('E1E0',atom4,degr4,j_inv);
end; // checkbox69

if form1.CheckBox85.Checked then // e1 + e2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1e2',atom4,degr4,j_inv);
end; // checkbox85

if form1.CheckBox95.Checked then // e1 +e3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1e3',atom4,degr4,j_inv);
end; // checkbox95

if form1.CheckBox105.Checked then // e1 +p2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1p2',atom4,degr4,j_inv);
end; // checkbox105

if form1.CheckBox115.Checked then // e1 +p3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1p3',atom4,degr4,j_inv);
end; // checkbox115

if form1.CheckBox125.Checked then // e1 +p4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1p4',atom4,degr4,j_inv);
end; // checkbox125

if form1.CheckBox135.Checked then // e1 +s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1s2',atom4,degr4,j_inv);
end; // checkbox135

if form1.CheckBox55.Checked then // e1 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1s2',atom4,degr4,j_inv);
end; // checkbox55

if form1.CheckBox45.Checked then // e1 +nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,1);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e1nn',atom4,degr4,j_inv);
end; // checkbox39
// block ec1 end

// ****************************************  block ec2 start
if form1.CheckBox63.Checked then // E2 - E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('E2E0',atom4,degr4,j_inv);
end; // checkbox63

if form1.CheckBox73.Checked then // E2 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('E2E1',atom4,degr4,j_inv);
end; // checkbox73

if form1.CheckBox93.Checked then // e2 +e3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2e3',atom4,degr4,j_inv);
end; // checkbox93

if form1.CheckBox103.Checked then // e2 +p2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2p2',atom4,degr4,j_inv);
end; // checkbox103

if form1.CheckBox113.Checked then // e2 +p3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2p3',atom4,degr4,j_inv);
end; // checkbox109

if form1.CheckBox123.Checked then // e2 +p4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2p4',atom4,degr4,j_inv);
end; // checkbox123

if form1.CheckBox133.Checked then // e2 +s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2s2',atom4,degr4,j_inv);
end; // checkbox133

if form1.CheckBox53.Checked then // e2 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2s3',atom4,degr4,j_inv);
end; // checkbox53

if form1.CheckBox43.Checked then // e2 +nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,2);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e2nn',atom4,degr4,j_inv);
end; // checkbox43

// block ec2 end  ======================================================
// ****************************************  block ec3 start
if form1.CheckBox60.Checked then // E3 - E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('E3E0',atom4,degr4,j_inv);
end; // checkbox60

if form1.CheckBox70.Checked then // E3 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('E3E1',atom4,degr4,j_inv);
end; // checkbox70

if form1.CheckBox80.Checked then // E3 - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('E3E2',atom4,degr4,j_inv);
end; // checkbox80

if form1.CheckBox100.Checked then // e3 +p2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e3p2',atom4,degr4,j_inv);
end; // checkbox100

if form1.CheckBox110.Checked then // e3 +p3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e3p3',atom4,degr4,j_inv);
end; // checkbox110

if form1.CheckBox120.Checked then // e3 +p4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e3p4',atom4,degr4,j_inv);
end; // checkbox123

if form1.CheckBox130.Checked then // e3 +s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e3s2',atom4,degr4,j_inv);
end; // checkbox130

if form1.CheckBox50.Checked then // e3 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e3s3',atom4,degr4,j_inv);
end; // checkbox50

if form1.CheckBox40.Checked then // e3 +nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,3);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('e3nn',atom4,degr4,j_inv);
end; // checkbox43

// block ec3 end  ======================================================

// ****************************************  block pt2 start
if form1.CheckBox58.Checked then // P2-E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P2E0',atom4,degr4,j_inv);
end; // checkbox60

if form1.CheckBox68.Checked then // P2 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P2E1',atom4,degr4,j_inv);
end; // checkbox70

if form1.CheckBox78.Checked then // P2 - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P2E2',atom4,degr4,j_inv);
end; // checkbox78

if form1.CheckBox88.Checked then // P2 - E3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P2E3',atom4,degr4,j_inv);
end; // checkbox100

if form1.CheckBox108.Checked then // p2 +p3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p2p3',atom4,degr4,j_inv);
end; // checkbox108

if form1.CheckBox118.Checked then // p2 + p4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p2p4',atom4,degr4,j_inv);
end; // checkbox118

if form1.CheckBox128.Checked then // p2 + s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p2s2',atom4,degr4,j_inv);
end; // checkbox128

if form1.CheckBox48.Checked then // p2 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p2s3',atom4,degr4,j_inv);
end; // checkbox48

if form1.CheckBox38.Checked then // p2 + nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,4);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p2nn',atom4,degr4,j_inv);
end; // checkbox43

// block pt2 end  ======================================================

// ****************************************  block pt3 start
if form1.CheckBox61.Checked then // P3-E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P3E0',atom4,degr4,j_inv);
end; // checkbox61

if form1.CheckBox71.Checked then // P3 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P3E1',atom4,degr4,j_inv);
end; // checkbox71

if form1.CheckBox81.Checked then // P2 - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P3E2',atom4,degr4,j_inv);
end; // checkbox81

if form1.CheckBox91.Checked then // P3 - E3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P3E3',atom4,degr4,j_inv);
end; // checkbox100

if form1.CheckBox101.Checked then // P3 - P2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P3P2',atom4,degr4,j_inv);
end; // checkbox101

if form1.CheckBox121.Checked then // p3 + p4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p3p4',atom4,degr4,j_inv);
end; // checkbox118

if form1.CheckBox131.Checked then // p3 + s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p3s2',atom4,degr4,j_inv);
end; // checkbox131

if form1.CheckBox51.Checked then // p3 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p3s3',atom4,degr4,j_inv);
end; // checkbox51

if form1.CheckBox41.Checked then // p3 + nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,5);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p3nn',atom4,degr4,j_inv);
end; // checkbox43

// block pt3 end  ======================================================

// ****************************************  block pt4 start
if form1.CheckBox66.Checked then // P4-E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P4E0',atom4,degr4,j_inv);
end; // checkbox66

if form1.CheckBox76.Checked then // P4 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P4E1',atom4,degr4,j_inv);
end; // checkbox76

if form1.CheckBox86.Checked then // P4 - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P4E2',atom4,degr4,j_inv);
end; // checkbox86

if form1.CheckBox96.Checked then // P4 - E3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P4E3',atom4,degr4,j_inv);
end; // checkbox96

if form1.CheckBox106.Checked then // P4 - P2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P4P2',atom4,degr4,j_inv);
end; // checkbox106

if form1.CheckBox116.Checked then // P4 - P3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('P4P3',atom4,degr4,j_inv);
end; // checkbox116

if form1.CheckBox136.Checked then // p4 + s2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p4s2',atom4,degr4,j_inv);
end; // checkbox136

if form1.CheckBox56.Checked then // p4 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p3s3',atom4,degr4,j_inv);
end; // checkbox56

if form1.CheckBox46.Checked then // p4 + nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,9);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('p4nn',atom4,degr4,j_inv);
end; // checkbox46

// block pt4 end  ======================================================

// ****************************************  block vs2 start
if form1.CheckBox62.Checked then // S2 - E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2E0',atom4,degr4,j_inv);
end; // checkbox62

if form1.CheckBox72.Checked then // S2 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2E1',atom4,degr4,j_inv);
end; // checkbox72

if form1.CheckBox82.Checked then // S2 - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2E2',atom4,degr4,j_inv);
end; // checkbox82

if form1.CheckBox92.Checked then // S2 - E3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2E3',atom4,degr4,j_inv);
end; // checkbox92

if form1.CheckBox102.Checked then // S2 - P2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2P2',atom4,degr4,j_inv);
end; // checkbox102

if form1.CheckBox112.Checked then // S2 - P3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2P3',atom4,degr4,j_inv);
end; // checkbox112

if form1.CheckBox122.Checked then // S2 - P4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S2P4',atom4,degr4,j_inv);
end; // checkbox122

if form1.CheckBox52.Checked then // s2 +s3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('s2s3',atom4,degr4,j_inv);
end; // checkbox52

if form1.CheckBox42.Checked then // s2 + nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,6);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('s2nn',atom4,degr4,j_inv);
end; // checkbox42

// block vs2 end  ======================================================

// ****************************************  block vs3 start
if form1.CheckBox67.Checked then // S3- E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3E0',atom4,degr4,j_inv);
end; // checkbox62

if form1.CheckBox77.Checked then // S3 - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3E1',atom4,degr4,j_inv);
end; // checkbox77

if form1.CheckBox87.Checked then // S3 - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3E2',atom4,degr4,j_inv);
end; // checkbox87

if form1.CheckBox97.Checked then // S3 - E3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3E3',atom4,degr4,j_inv);
end; // checkbox97

if form1.CheckBox107.Checked then // S3 - P2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3P2',atom4,degr4,j_inv);
end; // checkbox107

if form1.CheckBox117.Checked then // S3 - P3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3P3',atom4,degr4,j_inv);
end; // checkbox117

if form1.CheckBox127.Checked then // S3 - P4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3P4',atom4,degr4,j_inv);
end; // checkbox127

if form1.CheckBox137.Checked then // S3 - S2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('S3S2',atom4,degr4,j_inv);
end; // checkbox137

if form1.CheckBox47.Checked then // s3 + nn
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,7);
x2 :=  do_ecx(adj,n_loc,k,8);
degr4:=inttostr( x1 + x2 )+'+';
atom4:=ListOfAtom[k];
insertSF('s3nn',atom4,degr4,j_inv);
end; // checkbox47

// block vs3 end  ======================================================

// ****************************************  block NNC start
if form1.CheckBox64.Checked then // NN - E0
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,0);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNE0',atom4,degr4,j_inv);
end; // checkbox62

if form1.CheckBox74.Checked then // NN - E1
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,1);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNE1',atom4,degr4,j_inv);
end; // checkbox74

if form1.CheckBox84.Checked then // NN - E2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,2);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNE2',atom4,degr4,j_inv);
end; // checkbox84

if form1.CheckBox94.Checked then // NN - E3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,3);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNE3',atom4,degr4,j_inv);
end; // checkbox94

if form1.CheckBox104.Checked then // NN - P2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,4);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNP2',atom4,degr4,j_inv);
end; // checkbox104

if form1.CheckBox114.Checked then // NN - P3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,5);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNP3',atom4,degr4,j_inv);
end; // checkbox114

if form1.CheckBox124.Checked then // NN - P4
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,9);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNP4',atom4,degr4,j_inv);
end; // checkbox124

if form1.CheckBox134.Checked then // NN - S2
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,6);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNS2',atom4,degr4,j_inv);
end; // checkbox134

if form1.CheckBox54.Checked then // NN - S3
for k:=1 to n_loc do
begin
inc(j_inv);
x1 :=  do_ecx(adj,n_loc,k,8);
x2 :=  do_ecx(adj,n_loc,k,7);
degr4:=inttostr( noabs(x1 - x2) )+'-';
atom4:=ListOfAtom[k];
insertSF('NNS3',atom4,degr4,j_inv);
end; // checkbox47

// block NNC end  ======================================================

////////////////////////////////////////////////////////
// Super Quadrat END                                  //
// ============ June 20, 2018 copules of LI1 + LI2    //
////////////////////////////////////////////////////////




///////////////////////////////////////////////
(**)

n_loc:=j_inv;

end; // do_mg_invariants


procedure take_out_squared_brackets(var sms:string; var j_sf:integer);
label restart,goodbye;
var k:integer;
    a,b,d:string;
    c:char;
begin

//showmessage(sms);

   k:=0;
   d:='';

   restart:

   a:='';

   repeat k:=k+1; if k>length(sms) then begin d:=d+a; goto goodbye; end;
   c:=sms[k];
   if c<>'[' then a:=a+c;
   until c='[';

   d:=d+a;

   b:='[';
   repeat k:=k+1; if k>length(sms) then goto goodbye;
   c:=sms[k];
   b:=b+c;
   until c=']';
   inc(j_SF);
   local_SF_list[J_SF]:=b;
   repeat
   local_Sf_list[j_sf]:=local_SF_list[j_sf] +'.';
   until length(local_sf_list[j_sf])=12;

//   showmessage( local_Sf_list[j_sf]+' '+IntToStr(j_Sf) );

   if k<length(sms) then goto restart;

goodbye:
sms:=d;
//showmessage('R= '+sms);
end; // take out aaa[x]bbb[y]ccc -> aaabbbccc + [x], [y]

// December 5,2022
// symmetry xyx xyyx and xyzyx  NB: x<>y

procedure do_xyx(var sms:string; var CWS:CWsName);     // January 3,2023
var k:integer;                                         // Fragment of Local Symmetry
    z:string;
    s:integer;
    xyx:integer;
begin
//if sms[1] in [')','(','[',']'] then s:=3 else s:=2;
s:=2; // January2,2023
tester3:='';

xyx:=0;
for k:=s to length(sms)-1 do
     begin
     if
     (
     (sms[k-1]=sms[k+1]) and ( sms[k-1]<>sms[k])
     )
     then
        begin
        inc(xyx);
        tester3:=tester3 + sms[k-1]+sms[k]+sms[k+1]+';';
        end;
     end; // k

     if xyx<20 then z:=IntToStr(xyx)
               else z:='#';

     CWS:='';
     CWS:=CWS+'[xyx'+z+']';
     repeat CWS:=CWS +'.'; until length(CWs)>=12;

end; // xyx

procedure do_xyyx(var sms:string; var CWS:CWsName);
var k:integer;
    z:string;
    s:integer;
    xyx:integer;
begin
//if sms[1] in [')','(','[',']'] then s:=4 else s:=3;
s:=3; // January2,2023
tester4:='';

xyx:=0;
for k:=s to length(sms)-2 do
     begin
     if
     (
     (sms[k-2]=sms[k+1]) and (sms[k-1]=sms[k]) and (sms[k-2]<>sms[k-1])
     )
     then
        begin
        inc(xyx);
        tester4:=tester4 + sms[k-2]+sms[k-1]+sms[k]+sms[k+1]+';';
        end;
     end; // k

     if xyx<20 then z:=IntToStr(xyx)
               else z:='#';

     CWS:='';
     CWS:=CWS+'[xyyx'+z+']';
     repeat CWS:=CWS +'.'; until length(CWs)>=12;

end; // xyyx

procedure do_xyzyx(var sms:string; var CWS:CWsName);
var k:integer;
    z:string;
    s:integer;
    xyx:integer;
begin
//if sms[1] in [')','(','[',']'] then s:=5 else s:=4;
s:=4; // January2,2023
tester5:='';

xyx:=0;
for k:=s to length(sms)-3 do
     begin
     if
     (
     (sms[k-2]=sms[k+2]) and (sms[k-1]=sms[k+1]) and (sms[k-2]<>sms[k-1])
     )
     then
        begin
        inc(xyx);
        tester5:=tester5 + sms[k-2]+sms[k-1]+sms[k]+sms[k+1]+sms[k+2]+';';
        end;
     end; // k

     if xyx<20 then z:=IntToStr(xyx)
               else z:='#';

     CWS:='';
     CWS:=CWS+'[xyzyx'+z+']';
     repeat CWS:=CWS +'.'; until length(CWs)>=12;

end; // xyzyx


procedure sms_in_SF(
var sms,cas:string;
var Local_SF_list:SFlist;
var N_loc:integer
);
Label out_s, out_ss, out_sss, NoNumbers, do_brackets;
var
    j_sms,            // number sumbols in SMILES
    j_sf,             // number of SFk
    positinSMILES,    // C(C(C) -> C(, C(, C(, C(, C( not C(, C(, c(

    k:integer;        //
    ch,               // Char for Hyper Code doing

    c1,c2,c3,c4,
    c5,c6,c7,c8,
    c9,cA,cB,cC, cX
    :char;            // for building SFk
    sms_copy,

    show:string;
    cc1, cc2, cc3, cc4, cc5, cc6, cc7, // cycles
    bb1, bb2, bb3, bb4, bb5, bb6, bb7, // Brackets i.e. ()
    Cis,                               // Cis / Trans

    d3,               // number of @ and/or @@
    n2,n3,            // numbers of the double and triple bonds
    I, F, cl, Br, ni, no, ns, np:integer;    // IOdine, fluorine, chlorinr, ... phosphorus

begin

j_SF  := 0;                     // number of SFk

sms_copy:=sms;

n_loc:=0;

if form1.CheckBox32.Checked
then
begin

do_MG_invariants(sms,cas,local_sf_list,n_loc);

end // working with molecular graph
;    // else  The attempt of a hybride of SMILES & Graph

sms:=sms_copy;


begin

j_sms := 0;
J_sf:=n_loc;

// Sep27,2022
// take out from SMILES fragments located in brackets [xxx...]
//
take_out_squared_brackets(sms,j_SF);

if level1 then
begin

//////////////////////////////////////////////////////////////////////

repeat

// First component
inc(j_sms); c1c2c3c4(sms,c1,c2,c3,c4,j_sms) ; positinSMILES:=j_sms;

begin

if c1=BAR then goto out_s;
//if c1='[' then goto do_brackets;

inc(j_SF);

//if j_SF>MaxSF then    showmessage('Too much SFk !');

 if j_sf>maxSF then
 begin
 show:='J_SF='+IntToStr(j_sf)+'  Max='+IntToStr(MaxSF);
 showmessage(show);
 end; // J_SF>MaxSF

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:=BAR;

if c1<>BAR then
begin
local_SF_list[j_SF][1]:=c1;
local_SF_list[j_SF][2]:=c2;
local_SF_list[j_SF][3]:=c3;
local_SF_list[j_SF][4]:=c4;
end; // c1<>BAR
{}
local_SF_list[j_SF]:='';
Local_SF_list[j_sf]:=local_SF_list[j_SF]+c1+c2+c3+c4;
Local_SF_list[j_sf]:=local_SF_list[j_SF]+'........';


//showmessage('1 '+sms+' '+IntToStr(j_sf)+' '+local_SF_list[j_SF]);
{}
end; // C1 <> Fin



until (sms[j_sms]=BCE) or (j_sms>length(sms));
out_s:
//////////////////////////////////////////////////////////////////////
end; // level1 i.e., the s
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

if level2 then
begin
j_sms:=0;
positinSMILES:=0;

repeat

if positinSMILES<>0 then j_sms:=positinSMILES;

// First component
inc(j_sms); c1c2c3c4(sms,c1,c2,c3,c4,j_sms) ; positinSMILES:=j_sms;
// Second component
inc(j_sms); c1c2c3c4(sms,c5,c6,c7,c8,j_sms) ;

if cri4(c1,c2,c3,c4)<Cri4(c5,c6,c7,c8) then
begin
cx:=c1; c1:=c5; c5:=cx;
cx:=c2; c2:=c6; c6:=cx;
cx:=c3; c3:=c7; c7:=cx;
cx:=c4; c4:=c8; c8:=cx;
end; // cri4>cri4

//if c1<>BCE then
//if c5<>BCE then

begin

if c1=BAR then goto out_ss;
if c5=BAR then goto out_ss;
//if c1='[' then goto out_ss;
//if c5='[' then goto out_ss;

inc(j_SF);

//if j_SF>MaxSF then    showmessage('Too much SFk !');

 if j_sf>maxSF then
 begin
 show:='J_SF='+IntToStr(j_sf)+'  Max='+IntToStr(MaxSF);
 showmessage(show);
 end; // J_SF>MaxSF

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:=BAR;

if c1<>BAR then
begin
local_SF_list[j_SF][1]:=c1;
local_SF_list[j_SF][2]:=c2;
local_SF_list[j_SF][3]:=c3;
local_SF_list[j_SF][4]:=c4;
end; // c1<>BAR
{}
if c5<>BAR then
begin
local_SF_list[j_SF][5]:=c5;
local_SF_list[j_SF][6]:=c6;
local_SF_list[j_SF][7]:=c7;
local_SF_list[j_SF][8]:=c8;
end; // c5<>BAR

{}
end; // Both components exist: C1 and C5 and c9 <> Fin

local_SF_list[j_SF]:='';
Local_SF_list[j_sf]:=local_SF_list[j_SF]+c1+c2+c3+c4+c5+c6+c7+c8;
Local_SF_list[j_sf]:=local_SF_list[j_SF]+'....';

//showmessage('2 '+sms+' '+IntToStr(j_sf)+' '+local_SF_list[j_SF]);

until (sms[j_sms]=BCE) or (j_sms>length(sms));

out_ss:
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
end; // level2 i.e., the ss
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

if level3 then
begin
positinSMILES:=0;
j_sms:=0;

repeat

if positinSMILES>0 then j_sms:=positinSMILES;

// First component
inc(j_sms); c1c2c3c4(sms,c1,c2,c3,c4,j_sms) ; positinSMILES:=j_sms;
// Second component
inc(j_sms); c1c2c3c4(sms,c5,c6,c7,c8,j_sms) ;
// Third component
inc(j_sms); c1c2c3c4(sms,c9,cA,cB,cC,j_sms) ;

if cri4(c1,c2,c3,c4)<Cri4(c9,cA,cB,cC) then
begin
cx:=c1; c1:=c9; c9:=cx;
cx:=c2; c2:=cA; cA:=cx;
cx:=c3; c3:=cB; cB:=cx;
cx:=c4; c4:=cC; cC:=cx;
end; // cri4>cri4

//if c1<>BCE then
//if c5<>BCE then
//if c9<>BCE then
begin

if c1=BAR then goto out_sss;
if c5=BAR then goto out_sss;
if c9=BAR then goto out_sss;
//if c1='[' then goto out_sss;
//if c5='[' then goto out_sss;
//if c9='[' then goto out_sss;

inc(j_SF);


 if j_sf>maxSF then
 begin
 show:='J_SF='+IntToStr(j_sf)+'  Max='+IntToStr(MaxSF);
 showmessage(show);
 end; // J_SF>MaxSF

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:=BAR;

if c1<>BAR then
begin
local_SF_list[j_SF][1]:=c1;
local_SF_list[j_SF][2]:=c2;
local_SF_list[j_SF][3]:=c3;
local_SF_list[j_SF][4]:=c4;
end; // c1<>BAR
{}
if c5<>BAR then
begin
local_SF_list[j_SF][5]:=c5;
local_SF_list[j_SF][6]:=c6;
local_SF_list[j_SF][7]:=c7;
local_SF_list[j_SF][8]:=c8;
end; // c5<>BAR

if c9<>BAR then
begin
local_SF_list[j_SF][9 ]:=c9;
local_SF_list[j_SF][10]:=cA;
local_SF_list[j_SF][11]:=cB;
local_SF_list[j_SF][12]:=cC;
end; // c9<>BAR

local_SF_list[j_SF]:='';
Local_SF_list[j_sf]:=local_SF_list[j_SF]+c1+c2+c3+c4+c5+c6+c7+c8+c9+cA+cB+cC;
//showmessage('3 '+sms+' '+IntToStr(j_sf)+' '+local_SF_list[j_SF]);
{}
end; // Both components exist: C1 and C5 <> Fin

until (sms[j_sms]=BCE) or (j_sms>length(sms));

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

out_sss:   // from preparation of the individual SSSk (not collective one)

end; // level3, i.e., the sss

// Sep 27, 2022 get status quo after take out squared brackets fragments

sms:=sms_copy;

if form1.CheckBox24.Checked then // AA-Chaos May17,2023
begin
inc(j_SF);
do_AAchaos(sms,local_SF_list[j_SF],n_loc); // preparation of the SAk = [chaosN]........
//zzz:=zzz + tester6;
end; //


if form1.checkbox22.checked then  // Index-VI  N, O, S, P
begin

inc(j_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='0';

                    local_SF_list[j_SF][1]:='N';
                    local_SF_list[j_SF][2]:='O';
                    local_SF_list[j_SF][3]:='S';
                    local_SF_list[j_SF][4]:='P';

if n_N (sms)>0 then local_SF_list[j_SF][5]:='1';
if n_O (sms)>0 then local_SF_list[j_SF][6]:='1';
if n_S (sms)>0 then local_SF_list[j_SF][7]:='1';
if n_P (sms)>0 then local_SF_list[j_SF][8]:='1';

//if n_c1 (sms)>0 then local_SF_list[j_SF][10]:='1';
//if n_c2 (sms)>0 then local_SF_list[j_SF][11]:='1';
//if n_c3 (sms)>0 then local_SF_list[j_SF][12]:='1';


end; // Index NOS


if form1.checkbox23.checked then  // Index-VII  F, Cl, Br,    HALOgens
begin

inc(j_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='0';

                    local_SF_list[j_SF][1]:='H';
                    local_SF_list[j_SF][2]:='A';
                    local_SF_list[j_SF][3]:='L';
                    local_SF_list[j_SF][4]:='O';

if n_F (sms)>0 then local_SF_list[j_SF][5]:='1';
if n_Cl(sms)>0 then local_SF_list[j_SF][6]:='1';
if n_Br(sms)>0 then local_SF_list[j_SF][7]:='1';
if n_I (sms)>0 then local_SF_list[j_SF][8]:='1';


//if n_c1 (sms)>0 then local_SF_list[j_SF][9 ]:='1';
//if n_c2 (sms)>0 then local_SF_list[j_SF][10]:='1';
//if n_c3 (sms)>0 then local_SF_list[j_SF][11]:='1';
// if n_c5 (sms)>0 then local_SF_list[j_SF][12]:='1';


end; // Index_HALO

if form1.checkbox25.checked then  // Index-BOND =, #, @
begin

inc(j_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='0';

                     local_SF_list[j_SF][1] :='B';
                     local_SF_list[j_SF][2] :='O';
                     local_SF_list[j_SF][3] :='N';
                     local_SF_list[j_SF][4] :='D';

if n_2  (sms)>0 then local_SF_list[j_SF][5] :='1';
if n_3  (sms)>0 then local_SF_list[j_SF][6] :='1';
if n_Rot(sms)>0 then local_SF_list[j_SF][7] :='1';

end; // Index_BOND

(* HARD ALL = BOND + NOSP + HALO *)
// May 20, 2016
if form1.checkbox27.checked then  // BOND - NOSP - HALO = ALL
begin

inc(j_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='0';

                     local_SF_list[j_SF][ 1] :='$';

if n_2  (sms)>0 then local_SF_list[j_SF][ 2]:='1';
if n_3  (sms)>0 then local_SF_list[j_SF][ 3]:='1';
if n_Rot(sms)>0 then local_SF_list[j_SF][ 4]:='1';

if n_N  (sms)>0 then local_SF_list[j_SF][ 5]:='1';
if n_O  (sms)>0 then local_SF_list[j_SF][ 6]:='1';
if n_S  (sms)>0 then local_SF_list[j_SF][ 7]:='1';
if n_P  (sms)>0 then local_SF_list[j_SF][ 8]:='1';

if n_F  (sms)>0 then local_SF_list[j_SF][ 9]:='1';
if n_Cl (sms)>0 then local_SF_list[j_SF][10]:='1';
if n_Br (sms)>0 then local_SF_list[j_SF][11]:='1';
if n_I  (sms)>0 then local_SF_list[j_SF][12]:='1';

end; // Index     BOND - NOSP - HALO = ALL
(**)

// April 1, 2020: total number of an element N, O, S, F, Cl, Br, =, #, @

if form1.checkbox11.checked then  // N
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='N';
Local_SF_list[j_sf][3]:='>';
nmr_in_c1c2c3c4(n_n(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // N

if form1.checkbox75.checked then  // O
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='O';
Local_SF_list[j_sf][3]:='>';
nmr_in_c1c2c3c4(n_O(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // O

if form1.checkbox126.checked then  // S
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='S';
Local_SF_list[j_sf][3]:='>';
nmr_in_c1c2c3c4(n_S(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // S

if form1.checkbox44.checked then  // F
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='F';
Local_SF_list[j_sf][3]:='>';
nmr_in_c1c2c3c4(n_F(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // F

if form1.checkbox83.checked then  // Cl
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='C';
Local_SF_list[j_sf][3]:='l';
Local_SF_list[j_sf][4]:='>';
nmr_in_c1c2c3c4(n_n(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // Cl

if form1.checkbox111.checked then  // Br
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='B';
Local_SF_list[j_sf][3]:='r';
Local_SF_list[j_sf][4]:='>';
nmr_in_c1c2c3c4(n_n(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // Br

if form1.checkbox57.checked then  // = n_DB
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='=';
Local_SF_list[j_sf][3]:='>';
nmr_in_c1c2c3c4(n_2(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // =

if form1.checkbox90.checked then  // # n_3
begin
inc(j_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[j_sf][k]:='.';
Local_SF_list[j_sf][1]:='<';
Local_SF_list[j_sf][2]:='#';
Local_SF_list[j_sf][3]:='>';
nmr_in_c1c2c3c4(n_3(sms), c1,c2,c3,c4);
Local_SF_list[j_sf][6]:=c1;
Local_SF_list[j_sf][7]:=c2;
Local_SF_list[j_sf][8]:=c3;
Local_SF_list[j_sf][9]:=c4;
end; // #

end; // @

// Atoms pairs proportions APP[1..8,1..8] of integer    January 10, 2020

if app[1,1]>0 then  // (FCl)
begin

inc(J_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';

                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][4] :='C';
                     local_SF_list[J_SF][5] :='l';
                     local_SF_list[J_SF][6] :=')';

IntInChar( app[1,1], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,1], c1, n_cl (sms) ); local_SF_list[J_SF][11] := c1;

if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;

end; // FCl

if app[1,2]>0 then  // (FBr)
begin

inc(J_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';

                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][4] :='B';
                     local_SF_list[J_SF][5] :='r';
                     local_SF_list[J_SF][6] :=')';

IntInChar( app[1,2], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,2], c1, n_br (sms) ); local_SF_list[J_SF][11] := c1;

if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;

end; // FBr

if app[1,3]>0 then  // (FN)
begin

inc(J_SF);              //

for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';

                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][5] :='N';
                     local_SF_list[J_SF][6] :=')';

IntInChar( app[1,3], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,3], c1, n_n  (sms) ); local_SF_list[J_SF][11] := c1;

if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;

end; // FN

if app[1,4]>0 then  // (FO)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][5] :='O';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[1,4], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,4], c1, n_o  (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // FO

if app[1,5]>0 then  // (FS)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][5] :='S';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[1,5], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,5], c1, n_S  (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // FS

if app[1,6]>0 then  // (FP)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][5] :='P';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[1,6], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,6], c1, n_p  (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // FP

if app[1,7]>0 then  // (F=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[1,7], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,7], c1, n_2  (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // F=

if app[1,8]>0 then  // (F=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='F';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[1,8], c1, n_f  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[1,8], c1, n_3  (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // F#

if app[2,2]>0 then  // (ClBr)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][4] :='B';
                     local_SF_list[J_SF][5] :='r';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,2], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,2], c1, n_br  (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // ClBr

if app[2,3]>0 then  // (ClN)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][5] :='N';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,3], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,3], c1, n_n   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // ClN

if app[2,4]>0 then  // (ClO)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][5] :='O';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,4], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,4], c1, n_O   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // ClN

if app[2,5]>0 then  // (ClS)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][5] :='S';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,5], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,5], c1, n_S   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // ClS

if app[2,6]>0 then  // (ClP)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][5] :='P';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,6], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,6], c1, n_P   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // ClP

if app[2,7]>0 then  // (Cl=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,7], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,7], c1, n_2   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // Cl=

if app[2,8]>0 then  // (Cl=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='C';
                     local_SF_list[J_SF][3] :='l';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[2,8], c1, n_cl  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[2,8], c1, n_3   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // Cl#

if app[3,3]>0 then  // (BrN)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='B';
                     local_SF_list[J_SF][3] :='r';
                     local_SF_list[J_SF][5] :='N';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[3,3], c1, n_Br  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[3,3], c1, n_N   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // BrN

if app[3,4]>0 then  // (BrO)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='B';
                     local_SF_list[J_SF][3] :='r';
                     local_SF_list[J_SF][5] :='O';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[3,4], c1, n_Br  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[3,4], c1, n_O   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // BrO

if app[3,5]>0 then  // (BrS)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='B';
                     local_SF_list[J_SF][3] :='r';
                     local_SF_list[J_SF][5] :='S';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[3,5], c1, n_Br  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[3,5], c1, n_S   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // BrS

if app[3,6]>0 then  // (BrP)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='B';
                     local_SF_list[J_SF][3] :='r';
                     local_SF_list[J_SF][5] :='P';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[3,6], c1, n_Br  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[3,6], c1, n_P   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // BrP

if app[3,7]>0 then  // (Br=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='B';
                     local_SF_list[J_SF][3] :='r';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[3,7], c1, n_Br  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[3,7], c1, n_2   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // Br=

if app[3,8]>0 then  // (Br#)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='B';
                     local_SF_list[J_SF][3] :='r';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[3,8], c1, n_Br  (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[3,8], c1, n_3   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // Br#

if app[4,4]>0 then  // (NO)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='N';
                     local_SF_list[J_SF][5] :='O';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[4,4], c1, n_N   (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[4,4], c1, n_O   (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // NO

if app[4,5]>0 then  // (NS)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='N';
                     local_SF_list[J_SF][5] :='S';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[4,5], c1, n_n (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[4,5], c1, n_s (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // NS

if app[4,6]>0 then  // (NP)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='N';
                     local_SF_list[J_SF][5] :='P';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[4,6], c1, n_n (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[4,6], c1, n_p (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // NP

if app[4,7]>0 then  // (NP)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='N';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[4,7], c1, n_n (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[4,7], c1, n_2 (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // N=

if app[4,8]>0 then  // (N#)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='N';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[4,8], c1, n_n (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[4,8], c1, n_3 (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // N#

if app[5,5]>0 then  // (OS)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='O';
                     local_SF_list[J_SF][5] :='S';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[5,5], c1, n_o (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[5,5], c1, n_s (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // OS

if app[5,6]>0 then  // (OP)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='O';
                     local_SF_list[J_SF][5] :='P';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[5,6], c1, n_o (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[5,6], c1, n_p (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // OP

if app[5,7]>0 then  // (O=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='O';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[5,7], c1, n_o (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[5,7], c1, n_2 (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // O=

if app[5,8]>0 then  // (O#)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='O';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[5,8], c1, n_o (sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[5,8], c1, n_3 (sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // O#

if app[6,6]>0 then  // (SP
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='S';
                     local_SF_list[J_SF][5] :='P';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[6,6], c1, n_s(sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[6,6], c1, n_p(sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // SP

if app[6,7]>0 then  // (S=
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='S';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[6,7], c1, n_s(sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[6,7], c1, n_2(sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // S=

if app[6,8]>0 then  // (S=
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='S';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[6,8], c1, n_s(sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[6,8], c1, n_3(sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // S#

if app[7,7]>0 then  // (P=)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='P';
                     local_SF_list[J_SF][5] :='=';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[7,7], c1, n_p(sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[7,7], c1, n_2(sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // P=

if app[7,8]>0 then  // (P#)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='P';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[7,8], c1, n_p(sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[7,8], c1, n_3(sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // P#

if app[8,8]>0 then  // (=#)
begin
inc(J_SF);              //
for k:=1 to MaxCharSF do Local_SF_list[J_SF][k]:='.';
                     local_SF_list[J_SF][1] :='(';
                     local_SF_list[J_SF][2] :='=';
                     local_SF_list[J_SF][5] :='#';
                     local_SF_list[J_SF][6] :=')';
IntInChar( app[8,8], c1, n_2(sms) ); local_SF_list[J_SF][ 9] := c1;
IntInChar( app[8,8], c1, n_3(sms) ); local_SF_list[J_SF][11] := c1;
if (local_SF_list[J_SF][9]='0') or (local_SF_list[J_SF][11]='0') then J_SF:=J_SF - 1;
end; // =#

// January 9, 2020
//////////////////////////////////////////////////////////////


goto NoNumbers;  // ======================= No quantify of SAk presence ...

// if posit here fragment it will be unexist fragment

NoNumbers:

///////////////////////////////////////////////////////////////////////////
// October18,2022
// xyx local symmetry fragment
///////////////////////////////////////////////////////////////////////////

zzz:=sms;

if form1.CheckBox59.Checked then
begin
inc(j_SF);
do_xyx(sms,local_SF_list[j_sf]); // preparation of the SAk = [xyxN]........
zzz:=zzz + tester3+local_sf_list[j_sf];
end; // do xyx

if form1.CheckBox98.Checked then
begin
inc(j_SF);
do_xyyx(sms,local_SF_list[j_sf]); // preparation of the SAk = [xyyxN]........
zzz:=zzz + tester4+local_sf_list[j_sf];
end; // do xyyx

if form1.CheckBox35.Checked then
begin
inc(j_SF);
do_xyzyx(sms,local_SF_list[j_sf]); // preparation of the SAk = [xyzyxN]........
zzz:=zzz + tester5+local_sf_list[j_sf];
end; // do xyzyx

if sms<>zzz then writeln(sym,zzz);     // December 2,2022

n_loc:=j_sf;

end; // proc sms_in_SF

function SMILES_defect(var SMILES,CAS:string; var local_SF_list:SFlist):real;
var k,j,No:integer;
    SMS_defect:real;
    NatSFk,
    CW_defect:real;
begin

sms_in_SF(SMILES,CAS,local_SF_list,n_loc);

SMS_defect:=0.0;

for k:=1 to n_loc do
begin

   NatSFk:= NaturalCW(LOcal_SF_list[k],No);
   CW_defect:=CWdefect[no];
   SMS_defect:=SMS_defect + CW_defect;

end; //k

SMILES_defect:=SMS_defect;

end; // SMILES_defect


function IIC_autonom(parol:char; var c0,c1:real; var DCW,PA:DCWPA;var types:TRNCLBTST):real;
var k,
    nplus,
    n_MAKET,
    nminus:integer;

    cc0,cc1,
    dc0,dc1,

    rez,
    d,
    plus,minus:real;
begin

c0c1(Train,DCW,PA,cc0,cc1,dc0,dc1);

plus:=0.0;
minus:=0.0;
nplus:=0;
nminus:=0;

for k:=1 to nsms do
if types[k]=parol then
begin
 d:=pa[k]-(c0+c1*dcw[k]);
 if d>0 then
  begin
   plus:=plus+d;
   inc(nplus);
  end
  else
  begin
    minus:=minus-d;
    inc(nminus);
  end;
end; // k

if (nplus=0) or (nminus=0) then
begin
//showmessage('Crakh in IIC_autonom');
//halt;
nplus:=1;
nminus:=1;
plus:=1;
minus:=1;
end; //

plus:=plus/nplus;
minus:=minus/nminus;

if plus>minus then rez:=minus/plus
              else rez:=plus/minus;

IIC_autonom:=rez*kfkr(parol,DCW,PA,types,n_MAKET);

end; // Index of Ideality of correlation IIC


procedure exchange(parol1,parol2:char);
label next;
var
     k:integer;
begin
for k:=1 to nsms do
begin
if types[k]=parol1 then begin types[k]:=parol2; goto next; end;
if types[k]=parol2 then begin types[k]:=parol1; goto next; end;
next:
end;
end; // exchange

function corcoef(var x,y:DCWPA; n:integer):real;
var a,b,sx,sy,sxx,syy,sxy:real;
    k:integer;
    f:text;
begin

//assign(f,'Ytest.txt');rewrite(f);
//for k:=1 to n do writeln(f,y[k]:9:4,x[k]:9:4);
//closefile(f);
//showmessage('see Ytext.txt');

sx:=0;
sy:=0;
sxx:=0;
syy:=0;
sxy:=0;

for k:=1 to n do
begin
 sx:=sx+x[k];
 sy:=sy+y[k];
 sxx:=sxx+sqr(x[k]);
 syy:=syy+sqr(y[k]);
 sxy:=sxy+x[k]*y[k];
end; // k

a:=n*sxy - sx*sy;
b:=sqrt( ( n*sxx - sqr(sx) ) * (n*syy-sqr(sy) ) );

//showmessage('a='+FloatToStrF(a,FFfixed,9,4)+' b='+ FloatToStrF(b,FFfixed,9,4) );

//if (n=0) or (abs(b)<10e-25) then showmessage('Problem in Corcoef');

corcoef:=sqr(a/b);

end; //corcoef

function Y_randomization(parol:char; var c0,c1:real; var DCW,PA:DCWPA;var types:TRNCLBTST):real;
 
var k,kk:integer;
    Nvld:integer;
    x,y:DCWPA;
    cc0,cc1,dc0,dc1:real;
    dR,r0:real;
    n1,n2:integer;
    z:real;
//    f:text;
begin

c0:=StrToFloat(form1.Edit4.Text);
c1:=StrToFloat(form1.Edit5.Text);

Nvld:=0;

for k:=1 to nsms do
if types[k]=parol then
begin
inc( Nvld );

 if Nvld>MaxSMS then
 begin
  showmessage('Validation set is too large :'+IntToStr(Nvld)+'>'+IntToStr(MaxSMS));
  halt;
 end; // Nvld>MaxSMS

x[Nvld]:=c0 + c1*dcw[k];
y[Nvld]:=pa[k];

end; // k

//assign(f,'Ytest.txt');rewrite(f);
//for k:=1 to Nvld do writeln(f,y[k]:9:4,x[k]:9:4);
//closefile(f);

RVLD:=corcoef(x,y,Nvld);

dr:=0;

for kk:=1 to Nvld do
begin
  for k:=1 to Nvld do
  begin

    repeat
     n1:=trunc(random*Nvld)+1;
     n2:=trunc(random*Nvld)+1;
    until n1<>n2;

    z:=y[n1];  y[n1]:= y[n2]; y[n2]:=z;

  end; // k
  dr := dr + corcoef(x,y,Nvld);
end; // kk

Y_randomization := dr / Nvld;

end; // Y_randomization

procedure doDefectSMILES;
var kk,k:integer; rez:real;
begin
for k:=1 to nsms do
begin
 DefectSMILES[k]:=off;
 for kk:=1 to nuc[k][0] do
 begin
//  Check_LimNI(nuc[k][kk]);
  DefectSMILES[k]:=DefectSMILES[k]+CWdefect[nuc[k][kk]];
 end; // kk
end; // k
end; // DoDefectSMILES

function FuncSplitDefect:real;
var  sum:real;
     k:integer;
begin
sum:=0.0;
for k:=1 to nsms do
sum:=sum+defectSMILES[k];
FuncSplitDefect:=sum;
end; // Func Split defect

procedure doDCWm;
var kk,k:integer; rez:real;
begin
for k:=1 to nsms do
begin
 dcw[k]:=off;
 for kk:=1 to nuc[k][0] do
 begin
//  Check_LimNI(nuc[k][kk]);
  dcw[k]:=dcw[k]*CW[probe,nuc[k][kk]];
 end; // kk
end; // k
// rez:=dcw[k]; dcw[k]:=sqrt((rez));
end; // DoDCW

procedure doDCWa;
var kk,k:integer; rez:real;
begin
for k:=1 to nsms do
begin
 dcw[k]:=off;
 for kk:=1 to nuc[k][0] do
 begin
//  Check_LimNI(nuc[k][kk]);
  if CWactive[nuc[k][kk]] then dcw[k]:=dcw[k]+CW[probe,nuc[k][kk]];  // February20,2025



 end; // kk
end; // k
// rez:=dcw[k]; dcw[k]:=sqrt((rez));
end; // DoDCWa

procedure DoDCW;
begin
if scheme='*' then DoDCWm else DoDCWa;
//DoDCWa;
end; // DoDCW

function q2_five_fold(var parol:char; var dcw,pa:DCWPA;var c0,c1:real):real;

var
    pred:array[1..maxsms] of real;
    ord:array[1..maxsms] of integer;
    nord:integer;
    c,k:integer;
    rcv,dc0,dc1:real;
    mean,sum1,sum2:real;
begin
//q2_five_fold:=0;
//exit;
// DoDCW;

nord:=0;
for k:=1 to nsms do
if types[k]=parol then begin inc(nord); ord[nord]:=k; end;

for k:=1 to nord-5 do
begin
types[ ord[k]   ]:=reject;
types[ ord[k+1] ]:=reject;
types[ ord[k+2] ]:=reject;
types[ ord[k+3] ]:=reject;
types[ ord[k+4] ]:=reject;

c0c1(parol,dcw,pa,c0,c1,dc0,dc1);
pred[ ord[k] ]:=c0+c1*dcw[ ord[k] ];

types[ ord[k]   ]:=parol;
types[ ord[k+1] ]:=parol;
types[ ord[k+2] ]:=parol;
types[ ord[k+3] ]:=parol;
types[ ord[k+4] ]:=parol;

end; // k

mean:=0.0;
c:=0;
for k:=1 to nsms do
if types[k]=parol then begin mean:=mean + pa [ k ]; c:=c+1; end;

if c >0 then mean:=mean/c else mean:=0;

sum1:=0.0; sum2:=0.0;
for k:=1 to nord do
begin
sum1:=sum1 + sqr( pa[ ord[k] ] - pred[ ord[k] ] );
sum2:=sum2 + sqr( pa[ ord[k] ] - mean           );
end; // k

if sum2>0 then q2_five_fold:=1-sum1/sum2 else q2_five_fold:=0;
end; // Q2_five_fold


function q2(var parol:char; var dcw,pa:DCWPA;var c0,c1:real):real;

var
    pred:array[1..maxsms] of real;
    ord:array[1..maxsms] of integer;
    nord:integer;
    c,k:integer;
    rez,
    rcv,dc0,dc1:real;
    mean,sum1,sum2:double;
begin

//q2:=0;
//exit;

// DoDCW;

nord:=0;
for k:=1 to nsms do
if types[k]=parol then begin inc(nord); ord[nord]:=k; end;

for k:=1 to nord do
begin
types[ ord[k] ]:=reject;
c0c1(parol,dcw,pa,c0,c1,dc0,dc1);
pred[ ord[k] ]:=c0+c1*dcw[ ord[k] ];
types[ ord[k] ]:=parol;
end; // k

mean:=0.0;
c:=0;
for k:=1 to nsms do
if types[k]=parol then begin mean:=mean + pa [ k ]; c:=c+1; end;
if c >0 then mean:=mean/c else mean:=0;

sum1:=0.0; sum2:=0.0;
for k:=1 to nord do
begin
sum1:=sum1 + sqr( pa[ ord[k] ] - pred[ ord[k] ] );
sum2:=sum2 + sqr( pa[ ord[k] ] - mean           );
end; // k

if sum2>0 then rez:=1-sum1/sum2 else rez:=0;
if rez<0.01 then rez:=0.0; // November18,2024 q2 should be more zero

q2:=rez;

end; // Q2



function ccc(parol:char;var x,y:DCWPA;var types:TRNCLBTST; var n:integer):real;
Label outof;
var k:integer;
    rez,  cc0,cc1,dc0,dc1,
    ax,ay:real;
    sum_xk_ax, sum_yk_ay, sum_xy : real;
begin


rez:=0;
n:=0;

ax:=0.0;
ay:=0.0;

c0c1(train,x,y,cc0,cc1,dc0,dc1);

for k:=1 to nsms do
if types[k]=parol then
begin
 inc(n);
 ax:=ax+ ( cc0 + cc1 * x[k] );
 ay:=ay+ y[k];
end; // k

if n=0 then goto outof;

 ax:=ax / n;
 ay:=ay / n;

 sum_xk_ax:=0.0;
 sum_yk_ay:=0.0;
 sum_xy   :=0.0;

for k:=1 to nsms do
if types[k]=parol then
begin
  sum_xk_ax := sum_xk_ax + sqr( cc0+cc1*x[k] - ax );
  sum_yk_ay := sum_yk_ay + sqr( y[k] - ay );
  sum_xy    := sum_xy + (cc0+cc1*x[k] - ax)*(y[k] - ay)
end; // k

rez:=2*sum_xy / ( sum_xk_ax + sum_yk_ay + n*sqr(ax-ay) );

outof:

ccc:=rez;
end; // ccc


procedure IdealizationAPCV(var dcw,pa:DCWPA);
var c0,c1, dc0, dc1:real;
    delta:array[1..maxsms] of real;
    k:integer;
    maxCLBVLD,
    minTRNiTRN : real;
    kclbvld,
    kTRNiTRN:integer;
    c:char;
begin
c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1 );
for k:=1 to nsms do delta[k]:=abs(c0+c1*dcw[k] - pa[k]);

maxCLBVLD:=0.0; kclbvld:=0;
for k:=1 to nsms do
if (types[k]=test ) or (types[k]=valid) then
    begin
    if delta[k]>maxCLBVLD then
        begin
        maxCLBVLD:=delta[k];
        kclbvld:=k;
        end; // delta > max
    end; // calib or valid

minTRNiTRN:=100000.0; kTRNiTRN:=0;
for k:=1 to nsms do
if (types[k]=train) or (types[k]=calib) then
    begin
    if delta[k]<minTRNiTRN then
        begin
        minTRNiTRN:=delta[k];
        kTRNiTRN:=k;
        end; // delta > max
    end; // calib or valid

c:=types[kCLBvld]; types[kclbvld]:=types[kTRNiTRN]; types[kTRNiTRN]:=c;

end; // Idealization APCV

procedure IdealizationAPC(var dcw,pa:DCWPA);
var c0,c1, dc0, dc1:real;
    delta:array[1..maxsms] of real;
    k:integer;
    maxCLBVLD,
    minTRNiTRN : real;
    kclbvld,
    kTRNiTRN:integer;
    c:char;
begin
c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1 );
for k:=1 to nsms do delta[k]:=abs(c0+c1*dcw[k] - pa[k]);

maxCLBVLD:=0.0; kclbvld:=0;
for k:=1 to nsms do
if (types[k]=test ) then         // June5,2024 Indeed APC not APCV
    begin
    if delta[k]>maxCLBVLD then
        begin
        maxCLBVLD:=delta[k];
        kclbvld:=k;
        end; // delta > max
    end; // calib or valid

minTRNiTRN:=100000.0; kTRNiTRN:=0;
for k:=1 to nsms do
if (types[k]=train) or (types[k]=calib) then
    begin
    if delta[k]<minTRNiTRN then
        begin
        minTRNiTRN:=delta[k];
        kTRNiTRN:=k;
        end; // delta > max
    end; // calib or valid

c:=types[kCLBvld]; types[kclbvld]:=types[kTRNiTRN]; types[kTRNiTRN]:=c;

end; // Idealization APC


procedure idealization;
var k,n:integer;
begin
n := trunc(  StrToFloat(form1.Edit54.Text)*nsms  ); // October 29,2024
if APCV then for k:=1 to n do idealizationAPCV(dcw,pa)
        else for k:=1 to n do idealizationAPC (dcw,pa);
end; // idelaization

procedure dokk(parol:char; var x,y:DCWPA; c0,c1:real; var k1,k2:real);
var sxy, sx2, sy2:real;
    k,kk:integer;
    xx,yy:DCWPA;
    f:textfile;
begin                         // xx - calculation
kk:=0;                        // yy - experiment
for k:=1 to nsms do
if types[k]=parol then
begin
inc(kk);
xx[kk]:=c1*x[k]+c0;
yy[kk]:=   y[k];
end; // parol

//assign(f,'dokk');
//rewrite(f);
//for k:=1 to kk do writeln(f,yy[k]:9:4,xx[k]:9:4);
//close(f);

sxy:=0; sx2:=0; sy2:=0;
for k:=1 to kk do
begin
sxy:=sxy+xx[k]*yy[k];
sx2:=sx2+sqr(xx[k]);
sy2:=sy2+sqr(yy[k]);
end; // kk
IF sy2>0 then k1:=sxy/sy2 else k1:=0;
if sx2>0 then k2:=sxy/sx2 else k2:=0;
end; // dokk

function kfkrw(parol:char; x,y:DCWPA;var n:integer):real;
//label work;
var r1,r2:real;
    csi,   // correlation saturation index January4,2024
    xIIC,
    xCCI,
    IIC_CLB,
    IIC_iTRN,
    CCI_CLB,
    CCI_iTRN,
    cc0,cc1,c0,c1, dc0,dc1, k1, k2:real;
begin

xIIC:=0.0;
xCCI:=0.0;
csi :=0.0;

r1:=( kfkr(Train,x,y,types,n) );
r2:=( kfkr(Calib,x,y,types,n) );

// add:=abs(r1-r2)*0.1;

(**)
if form1.CheckBox26.Checked then // MAE-Index of Ideality of correlation MIIC
begin

     c0c1(Train,x,y,cc0,cc1,dc0,dc1);

   if IIC_style = 0 then
    begin
         xIIC:=IIC(test ,cc0,cc1,dcw,pa,types)*dKweight;
    end;


   if IIC_style = 1 then
    begin
         xIIC:=IIC(calib,cc0,cc1,dcw,pa,types)*dKweight;
    end;

    if IIC_style = 2 then
     begin
         IIC_CLB :=IIC(test ,cc0,cc1,dcw,pa,types);
         IIC_iTRN:=IIC(calib,cc0,cc1,dcw,pa,types);
         xIIC:=(IIC_CLB + IIC_iTRN)*dKweight;
     end;

end;

// November 1, 2019
if form1.CheckBox7.Checked then // Correlation Intensity Index CCI (february 4, 2020)
begin

   if CCI_style = 0 then
    begin
     xCCI:=CCI(test ,cc0,cc1,dcw,pa,types)*dCweight;
    end;

   if CCI_style = 1 then
    begin
     xCCI:=CCI(calib,cc0,cc1,dcw,pa,types)*dCweight;
    end;

   if CCI_style = 2 then
    begin
     CCI_CLB:=CCI(test,cc0,cc1,dcw,pa,types);
     CCI_iTRN:=CCI(calib,cc0,cc1,dcw,pa,types);
     xCCI:=( CCI_CLB + CCI_iTRN )*dCweight;
    end;

end;

// january4,2024
if Form1.chk1.Checked then
begin

csi:=RGindex(Test,DCW,pa)*CCCP;
   if CCCP_style = 0 then
    begin
     csi:=RGindex(Test,DCW,pa)*CCCP;
    end;

   if CCCP_style = 1 then
    begin
    csi:=RGindex(Calib,DCW,pa)*CCCP;
    end;

   if CCCP_style = 2 then
    begin
     csi:=( RGindex(Test,DCW,pa) + RGindex(Calib,DCW,pa) )*CCCP;
    end;

end; // CCCP checked

kfkrw:=r1 + r2 + xIIC + xCCI +csi - ( abs(r1-r2)*dRweight );

end; // kfkrw[work]


function NactSFk:integer; // number of active (not blocked) SFk
var k,sum:integer;
begin
sum:=0;
for k:=1 to n_glb do
//if cw[1,k]<>off then inc(sum);
if CWactive[k] then inc(sum); // April6,2023
NactSFk:=sum;
end; // NactSFk

Function N_SMILESs_with_SFk(parol:char;var SFk:CWsname):integer; // number of SMILES with SFk
Label next_ksms;
var sum,ksms,i:integer;
begin
sum:=0;
for ksms:=1 to nsms do
if types[ksms]=parol then
begin
 sms_in_SF(sms[ksms],cas[ksms],local_SF_list,n_loc);
  for i:=1 to n_loc do
  if CWsNameSame( local_SF_list[i],SFk ) then
   begin
   inc(sum);
   goto next_ksms;
  end; // local_SFi=Global_SFk
 next_ksms:
end; // types=parol & ksms

N_SMILESs_with_SFk:=sum;

end; // N_SMILESs_with_SFk

function number_SMILES_in_SET(parol:char):integer;
var sum,k:integer;
begin
sum:=0;
for k:=1 to nsms do
if types[k]=parol then inc(sum);
number_SMILES_in_SET:=sum;
end; // number SMILES in SET

function stringsduplicates(var s1,s2:string):boolean;
label outof;
var k:integer;
    len1,len2 // lengths of the strings s1 and s2
    :integer;
    rez:boolean;
begin
rez:=false;

len1:=length(s1);
len2:=length(s2);
if len1<>len2 then goto outof;

for k:=1 to len1 do
if s1[k]<>s2[k] then goto outof;

rez:=TRue;

outof:
stringsduplicates:=rez;
end; // stringsduplicates

procedure CheckSMILESduplicates(var dup:integer; deldup:boolean);
var k,kk:integer;
    r,
    f:text;
begin
dup:=0;

if (form1.CheckBox33.Checked) or (form1.CheckBox34.Checked) then
begin
assign(f,DuplicatesFileName); rewrite(f);
end;

if (form1.CheckBox33.Checked) then
for k:=1 to nsms-1 do
for kk:=k+1 to nsms do
if stringsduplicates(sms[k],sms[kk])
then
begin

//types[ k]:=Reject;
writeln(f,'#',k :5,' ',types[k] ,' CAS=',cas[k ],' SMILES=',sms[k ],' EndPoint=',pa[k ]:9:3);
writeln(f,'#',kk:5,' ',types[kk],' CAS=',cas[kk],' SMILES=',sms[kk],' Endpoint=',pa[kk]:9:3);
writeln(f,'...SMILES-duplicate');

if deldup then
begin
types[ k]:=Reject;
//types[kk]:=Reject;
end; // deldup

inc(dup);
end; // kk,k

if (form1.CheckBox34.Checked) then
for k:=1 to nsms-1 do
for kk:=k+1 to nsms do
if stringsduplicates(CAS[k],CAS[kk])
then
begin
//types[ k]:=Reject;
writeln(f,'#',k :5,' ',types[k] ,' CAS=',cas[k ],' SMILES=',sms[k ],' EndPoint=',pa[k ]:9:3);
writeln(f,'#',kk:5,' ',types[kk],' CAS=',cas[kk],' SMILES=',sms[kk],' Endpoint=',pa[kk]:9:3);
writeln(f,'...CAS-duplicate');

if deldup then
begin
types[ k]:=Reject;
//types[kk]:=Reject;
end; // deldup

inc(dup);
end; // kk,k

if (form1.CheckBox33.Checked) or (form1.CheckBox34.Checked) then
if dup=0 then writeln(f,'Duplicates are not detected');

if (form1.CheckBox33.Checked) or (form1.CheckBox34.Checked) then closefile(f);


if deldup then
begin
assign(f,form1.Edit1.Text); rewrite(f);
assign(r,'#removed.txt'); rewrite(r);
for k:=1 to nsms do
begin
  if types[k]<>Reject
   then
   begin
   write(f,types[k],CAS[k],' ');
   for kk:=1 to length(SMS[k])-1 do write(f,sms[k,kk]);
   writeln(f,pa[k]:9:3);
   end // types<>Reject in Totalset'.txt
   else
   begin
   write(r,types[k],CAS[k],' ');
   for kk:=1 to length(SMS[k])-1 do write(r,sms[k,kk]);
   writeln(r,pa[k]:9:3);
   end // in #removed.txt
end; // k
closefile(f);
close(r);
halt;
end;//

end; // CheckCASDuplicates


procedure loadSMILES(fname:string);
label outof, nextksms;
var f,e:textfile;
    mss:string;
    r, // for dialog message
//    k,j,
    dup, // the number of duplicates
    ksms:integer;
    x:real;
    nofile:boolean;

begin
MaxSMILESlength2:=50;

DotInSMILES:='';

nofile:=false;
assignfile(f,fname);
{$I-}
reset(f);
{$I+}
if IOResult <> 0 then
begin
begin
showmessage('File '+Fname+' not found'+#13+
'The search is impossible, program will be halted');
halt;
end;
nofile:=true;
goto outof;
end;  // IOresult <>0

assign(e,'#CheckUp.txt'); rewrite(e);

ksms:=0;
repeat inc(ksms);

if ksms>MaxSMS-3 then   // MAIN INPUT
begin
showmessage('Too much SMILES: Program will be halted'); halt;
end;
read_sms(f,types[ksms],cas[ksms],sms[ksms],chana[ksms],pa[ksms],ksms);

CASLV[ksms]:=cas[ksms]; // April17,2024 repair saving #TotalSetLV.txt
//showmessage('CASLV='+CASLV[ksms]);

writeln(e,cas[ksms],' ',SMS[ksms],pa[ksms]:9:3);

if dotinsmiles<>'' then
if form1.CheckBox32.Checked then
begin
if not userinformed then
// showmessage('Involving of graphs is impossible: there are "." or "*"');
userinformed:=True;
//halt;
end;
// December 1, 2011: An attempt to carry out Classification Model 0,1

//if classification then
begin
pa01[ksms]:=pa[ksms];
//pa[ksms]:=pa[ksms] + (0.5-random)*0.1;
end;

if length(sms[ksms])>MaxSMILESlength2 then MaxSMILESlength2:=length(sms[ksms]);

//if PAmodify then begin x:=pa[ksms]; pa[ksms]:=ln(x)/ln(10.0); end;

if form1.radiobutton2.checked then
begin
if types[ksms]=Calib then begin types[ksms]:=Train; end;
end; // (TC):t


// showmessage(IntToStr(ksms)+' '+types[ksms]+' '+cas[ksms]+' '+sms[ksms]+' '+chana[ksms]);

// form1.Label1.caption:=CAS[ksms];


nextksms:
until eof(f);
nsms:=ksms;
closefile(f);
closefile(e);

//assign(f,'bee');rewrite(f);
//for k:=1 to nsms do
//begin
//write(f,types[k],cas[k],' ');
//for j:=1 to length(sms[k])-1 do write(f,sms[k,j]);
//writeln(f,pa[k]:9:3);
//end;
//closefile(f);showmessage('x-log(1/x) completed, now halt');halt;

//if classification then
begin
min01:=pa01[1];
max01:=pa01[1];
for ksms:=1 to nsms do
begin
if pa01[ksms]>max01 then max01:=pa01[ksms];
if pa01[ksms]<min01 then min01:=pa01[ksms];
end; // min01, max01, middle01
middle01:=min01 + (max01 - min01)*0.5;
end; // classification

CheckSMILESduplicates(dup,False);

if dup<>0 then
begin
mss:='There are duplicates (N='+IntToStr(dup)+').'
+#13+'Please see File '+duplicatesFileName
+#13+'Delete duplicates [y]?';

r:=messageDlg(mss,mtConfirmation,[mbYes,mbNo],0);
if r=mrNo then goto outof;
if r=mrYes then  CheckSMILESduplicates(dup,True);
//if r=mrCancel then goto outof;
end; // dup


outof:
if nofile then showmessage('Load SMILES was not succesful: no data!');

end; // loadSMILES


procedure SplitInfo;
var nact,sa,sms:integer;
    III,IIO,IOI,IOO,OII,OIO,OOI:integer;
begin

Nact:=NactSFk;
III:=0; IIO:=0; IOI:=0; IOO:=0; OII:=0; OIO:=0; OOI:=0;

for sa:=1 to n_glb do
//if cw[probe,sa]<>off then // April12,2023
if CWactive[sa] then // April12,2023
begin

if SMILESAk='S' then
begin
if (TRNs[sa]>=LimNI) and (CLBs[sa]>=1) and (TSTs[sa]>=1) then inc(III);
if (TRNs[sa]>=LimNI) and (CLBs[sa]>=1) and (TSTs[sa]< 1) then inc(IIO);
if (TRNs[sa]>=LimNI) and (CLBs[sa]< 1) and (TSTs[sa]>=1) then inc(IOI);
if (TRNs[sa]>=LimNI) and (CLBs[sa]< 1) and (TSTs[sa]< 1) then inc(IOO);
if (TRNs[sa]<=LimNI) and (CLBs[sa]>=1) and (TSTs[sa]>=1) then inc(OII);
if (TRNs[sa]<=LimNI) and (CLBs[sa]>=1) and (TSTs[sa]< 1) then inc(OIO);
if (TRNs[sa]<=LimNI) and (CLBs[sa]< 1) and (TSTs[sa]>=1) then inc(OOI);
end; // LIM SMILES = LimS

(**
if SMILESAk='N' then
begin
if (TRN[sa]>=LimNI) and (CLB[sa]>=1) and (TST[sa]>=1) then inc(III);
if (TRN[sa]>=LimNI) and (CLB[sa]>=1) and (TST[sa]< 1) then inc(IIO);
if (TRN[sa]>=LimNI) and (CLB[sa]< 1) and (TST[sa]>=1) then inc(IOI);
if (TRN[sa]>=LimNI) and (CLB[sa]< 1) and (TST[sa]< 1) then inc(IOO);
if (TRN[sa]<=LimNI) and (CLB[sa]>=1) and (TST[sa]>=1) then inc(OII);
if (TRN[sa]<=LimNI) and (CLB[sa]>=1) and (TST[sa]< 1) then inc(OIO);
if (TRN[sa]<=LimNI) and (CLB[sa]< 1) and (TST[sa]>=1) then inc(OOI);
end; // LIM attributes in general = LimN
(**)
end; // next SA, i.e., SMILES attribute

form1.edit13.text:= IntToStr(III);
form1.edit12.text:= IntToStr(IIO);
form1.edit8.text := IntToStr(IOI);
form1.edit32.text:= IntToStr(IOO);
form1.edit33.text:= IntToStr(III+IIO+IOI+IOO);

form1.edit2.Text:= FloatToStrF(density,FFfixed,9,3);


if form1.radiobutton1.checked
then form1.edit36.Text:= FloatToStrF(iii/Nact*100,FFfixed,7,0)
else form1.edit36.Text:= FloatToStrF(ioi/Nact*100,FFfixed,7,0);

end; // splitinfo

Function Wstyle(CWi:real):boolean;
label outof;
var rez:boolean;
begin
rez:=true;
if Save_all_CWs then goto outof;
if CWi=off then rez:=false;
outof:
Wstyle:=rez;
end; // Wstyle

function sms_contains_SFk  // yes or not ?
(var ks:integer; // number of SMILES
 var ka  // number of attribute
:integer
):boolean;
Label outoff;
var rez:boolean;
    j,k:integer;
begin
rez:=False;
for k:=1 to nuc[ks,0] do
begin
(*
form1.Label48.Caption:='';
for j:=1 to nuc[ks,0] do
form1.Label48.Caption:= form1.Label48.Caption+inttostr(nuc[ks,j]);

showmessage(sms[ks]+#13+
' SMS='+inttostr(ks)+' '+' SA='+inttostr(ka)+#13+
inttostr(nuc[ks,k])+' : '+inttostr(k)+' -> '+inttostr(nuc[ks,0]));
*)
if ka=nuc[ks,k] then begin rez:=true; goto outoff; end;
end;
outoff:
//if rez then showmessage('SA in SMILES!');
sms_contains_SFk:=rez;
end; // sms_contains_SFk

function Nminus (
parol:char;  // TRN, CLB, TST
probe,
i:integer;   // number of SA
s,c0,c1:real // TRN standar error and regerssion coefficients
):integer;

var k,sum:integer;
    st,
    expcal:real;
begin
st:=s+s;
sum:=0;
for k:=1 to nsms do
if types[k]=parol then
if sms_contains_SFk(k,i) then
begin

expcal:=pa[k]-c0-c1*DCW[k];
if -expcal>st then inc(sum);
(*
showmessage(types[k]+
' c0='+FloatToStrF(c0,FFfixed,12,7)+' c1='+floattostrf(c1,FFfixed,12,5)+#13
+' expcal='+floattostrf(expcal,FFfixed,12,5)+' PA['+inttostr(k)+']='+floattostrf(pa[k],FFfixed,12,5) );
*)
end;
Nminus:=sum;
end; // Nminus

function Nplus (
parol:char;  // TRN, CLB, TST       
probe,
i:integer;   // number of SA
s,c0,c1:real // TRN standar error and regerssion coefficients
):integer;

var k,sum:integer;
    st,
    expcal:real;
begin
st:=s+s;
sum:=0;
for k:=1 to nsms do
if types[k]=parol then
if sms_contains_SFk(k,i) then
begin
expcal:=pa[k]-c0-c1*DCW[k];
if expcal>st then inc(sum);
end;
Nplus:=sum;
end; // Nplus

function ChangeR(
parol:char;
probe,
k:integer;
var x,y:DCWPA;
nsms:integer
):real;

var
   Rmemory,
//   rere,
   RSAk,
   CWmemory:real;
   nnn:integer;
begin

CWmemory:=CW[probe,k];
Rmemory:=kfkr(parol,x,y,types,nnn);

cw[probe,k]:=0.0;

dodcw;
RSAk:=kfkr(parol,x,y,types,nnn);
cw[probe,k]:=CWmemory;
dodcw;
//rere:=kfkr(parol,x,y,nnn);
(**
showmessage(
'Rstart='+floattostrf(rmemory,FFfixed,12,8)+
'  RSAk='+  floattostrf(rsak,FFfixed,12,8)+
'  Rere='+floattostrf(rere,FFfixed,12,8)
);
(**)


ChangeR:=Rmemory-RSAk;
end; // changeR

function parolisok(parol,kind:char):boolean;
var rez:boolean;
begin
(*
if parol=train then
begin
rez:= ( kind=train ) or (kind=calib);
end
else rez:=parol=kind;
*)
rez:=parol=kind;

parolisok:=rez;

end; // parolisok


function xiny(x,y:real):real; // x^y
begin
xiny := exp( y*ln(x) );
end; // xiny

//OPT-preparation
procedure SaveOptimizMatrix(zname,zname2:string);
label outof;
var z:textfile;
    r,    // for messageDLG about the TT
    i,j,
    ksms:integer;
    mss:string;
    nt,nv,ne:integer;
    colon:char;

    Nmr,  // Index variable for SA[nmr]
    MaxSFnmr,      // Max number of a SFk in the TRAINING set
    f2:integer;



    dTRN,          // d = SH(limN=0) - SH(limN<>0)
    dCLB,          // Change of the Shanon entropy for given limN
    dTST,          // in comparison with limN=0

    SH_TRN0,       // Total Shannon entropy for the TRN,CLB,TST if LimN=0
    SH_CLB0,
    SH_TST0,

    SH_TRN,       // Shannon entropy for TRN,CLB,TST for given LimN<>0
    SH_CLB,
    SH_TST,

    TTTRN0,        // Total number SAk in TRN,CLB,TST for LimN=0
    TTCLB0,
    TTTST0,

    dsp,           // dispersion in the qualification of SAk=PR(T) - PR(t)

    TT_TRN,        // Total number SAk in TRN,CLB,TST for given LimN<>0
    TT_CLB,
    TT_TST,
    ptc,           // P(SAk) for TRN or (TRN&CLB) in RELative PREvalence
    dc0,dc1,       // additional argument for c0c1 procedure
    c0,c1,st       // regerssion pa=c0+c1dcw, st standard error for TRN
                : real;

    txt:string;    // for messageDLG about the TT

    NsmsA, // N of active training set train
    NsmsP, // N of passive training set calib
    NsmsC  // N of calibration set test
    :integer;
    splitDef,
    NSD,     // Jan 11, 2018 Normalized Split defect
    SD:real; // local split defect P(SAk) in TRN - P(SAk) in TST
    Nact:integer; // the number of SFk which are not blocked
    denominator:real;
    N_A,N_I:integer; // how many SFk falls into active or inactive compounds
    aaa,bbb,ccc:real; // new defect F= (A, P, C), active training, passiva training and calibrartion set
begin

if SAS then goto OutOf;

NactiveCWs:=0;

NsmsA:=number_SMILES_in_SET(train);
NsmsP:=number_SMILES_in_SET(Calib);
NsmsC:=number_SMILES_in_SET(test );
Nact:=NactSFk;

colon:=':';

if IniCWs then
begin
n_glb:=0;
for ksms:=1 to nsms do
// if types[ksms]=Train then
begin
// showmessage(inttostr(ksms));
sms_in_SF(sms[ksms],cas[ksms],local_SF_list,n_loc);
do_global_SF_list(local_sf_list,n_loc,Global_SF_list,n_glb);
end; // ksms SMILES -> {SFk}
end; // IniCWs

marker:=1;

//ShowMessage('IniCWs is OK');

assignfile(z,zname);
{$I-}
rewrite(z);
{$I+}
if IOResult <> 0 then
begin
mss:='File '+ zname+' not good, Do restart of this program';
messageDLg(mss,mtInformation,[mbOK],0);
goto outof;
end;  // IOresult <>0

doDCW;

if not inicws then
begin
c0c1(train,dcw,pa,c0,c1,dc0,dc1);
st:=see(train,c0,c1);
// we have c0,c1, and st for calculation of SA characteristics as partisipant
// in outliers...
end; // not inicws

write(z,n_glb:3,
sqr(kfkr(Train,DCW,PA,types,nt)):9:4,
sqr(kfkr(Calib,DCW,PA,types,nv)):9:4,
sqr(kfkr(Test ,DCW,PA,types,ne)):9:4,
' Alpha=',alpha:5:1
);
{=============================================================
Calculation of the Trn, Clb, and Tst, i.e., numbers of the SFk
in the Training, Calibration, and test sets, respectively.
==============================================================
}

For i:=1 to maxSF do
begin
trn[i]:=0; Clb[i]:=0; Tst[i]:=0;
end; // next i

Trns[0]:=0; // N SMILES in Training
Clbs[0]:=0; // N SMILES in Calibration
Tsts[0]:=0; // N SMILES in Test

for ksms:=1 to nsms do
begin
 sms_in_SF(sms[ksms],cas[ksms],local_SF_list,n_loc);
// showmessage('Types '+IntToStr(ksms)+' '+types[ksms]);
 for i:=1 to n_loc do
 begin
(*
 if  (types[ksms]<>Train)
 and (types[ksms]<>Calib)
 and (types[ksms]<>test ) then showmessage('Types are lost!!! '+IntToStr(ksms));
*)

  if types[ksms]=Train then
  begin
  inc( Trn[ CWnumber(local_SF_list[i],n_glb) ] );

  if Trn[ CWnumber(local_SF_list[i],n_glb) ]>maxSFnmr
  then maxSFnmr:= Trn[ CWnumber(local_SF_list[i],n_glb) ];

  end; // numbers of the SFk in the training set

  if types[ksms]=Calib then inc( Clb[ CWnumber(local_SF_list[i],n_glb) ] );
  if types[ksms]=Test  then inc( Tst[ CWnumber(local_SF_list[i],n_glb) ] );
 end;
if types[ksms]=Train then inc( Trns[0] );
if types[ksms]=Calib then inc( Clbs[0] );
if types[ksms]=Test  then inc( Tsts[0] );
end; // ksms



writeln(z,' limNI=',limNI);

if Trns[0]=0 then Trns[0]:=-1; // in order to avoid
if Clbs[0]=0 then Clbs[0]:=-1; // division by zero
if Tsts[0]=0 then Tsts[0]:=-1; // in calculation of the Probabilities

{=============================================================
Here data on the Trn, Clb, and Tst is ready
==============================================================
}

{=============================================================
Calculation how much SFk happens in the Training, Calibration,
and Test sets = Trns, Clbs, and Tsts, respectively.
}

for i:=1 to n_glb do
begin
Trns[i]:=N_SMILESs_with_SFk(Train,Global_SF_list[i]);

CWactive[i]:=trns[i]>LimNi;

Clbs[i]:=N_SMILESs_with_SFk(Calib,Global_SF_list[i]);
Tsts[i]:=N_SMILESs_with_SFk(Test ,Global_SF_list[i]);
end; // i

{==============================================================
Here calculation of Trns, Clbs, Tsts is completed }


TT_TRN:=0.0;   // Total number of SAk in TRN,CLB,TST for given LimN<>0
TT_CLB:=0.0;
TT_TST:=0.0;

TTTRN0:=0.0;   // Total number of SAk in TRN,CLB,TST for LimN=0
TTCLB0:=0.0;
TTTST0:=0.0;

for i:=1 to n_glb do
begin
//write(z,i:3,' ');
for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]);

// if trn[i]=0 then cw[i]:=1.0;

//d1:=' '; if (trn[i]<limNi) and (tst[i]>0) then d1:='D'; // defects marker

//Check_LimNI(i); // check up: whether Trn of SFi is more LimNI ?
                // if not then CW(SFi)=1

f2:=ffP; if cw[probe,i]=off then f2:=1; // formats 0.9978178 == 1.0

writeln(z,
//d1,
CW[probe,i], // 
//colon,
i:7,
//colon,
Trn[i]:7,
//colon,
Clb[i]:7,
//colon,
Tst[i]:7,
//colon,
Trns[i]:7,
//colon,
Clbs[i]:7,
//colon,
Tsts[i]:7);


if cw[probe,i]<>off then
TT_TRN:=TT_TRN + trns[i];

if cw[probe,i]<>off then
TT_CLB:=TT_CLB + clbs[i];

if cw[probe,i]<>off then
TT_TST:=TT_TST + tsts[i];


TTTRN0:=TTTRN0 + trns[i];
TTCLB0:=TTCLB0 + clbs[i];
TTTST0:=TTTST0 + tsts[i];

end; // i: print list of SFk globally


if TT_CLB=0.0 then TT_CLB:=1.0;
if TTCLB0=0.0 then TTCLB0:=1.0;

txt:=
'N(SA)T='+FloatToStrF(TTTRN0,FFfixed,7,0)+' '+
'N(SA)C='+FloatToStrF(TTCLB0,FFfixed,7,0)+' '+
'N(SA)t='+FloatToStrF(TTTST0,FFfixed,7,0)+' Lim=0'+ #13 +

'M(SA)T='+FloatToStrF(TT_TRN,FFfixed,7,0)+' '+
'M(SA)C='+FloatToStrF(TT_CLB,FFfixed,7,0)+' '+
'M(SA)t='+FloatToStrF(TT_TST,FFfixed,7,0)+' Lim='+inttostr(LimNI)+ #13 +
'           Continue of calculation? Scheme is' + scheme;

if series='n' then
begin
r:=messageDLG(txt,mtConfirmation,[mbYes,mbNo,mbCancel],0);
if r=mrNO then goto outof;
if r=mrCancel then goto outof;
end;

writeln(z,nsms);

// print in view of the number of the SFk in Global List
for ksms:=1 to nsms do
begin

sms_in_SF(sms[ksms],cas[ksms],local_SF_list,n_loc);

write(z,types[ksms],n_loc:7);
for i:=1 to n_loc do
begin
write(z,CWnumber(local_SF_list[i],n_glb):12);
end;
writeln(z,pa[ksms]:10:3,' ',CAS[ksms]);
end; // sms Print of SMILES in SFk sequances

for ksms:=1 to nsms do writeln(z,sms[ksms]); // SMILES recorded in

closefile(z);

//zname[1]:='w';

assignfile(z,zname2);
{$I-}
rewrite(z);
{$I+}
if IOResult <> 0 then
begin
mss:='File '+ zname+' is not correct, this program will be halted.';
messageDLg(mss,mtInformation,[mbOK],0);

goto outof;
end;  // IOresult <>0


Writeln(z,'LIST OF STRUCTURAL ATTRIBUTES (SA) AND THEIR CORRELATION WEIGHTS');
writeln(z,DotInSMILES);
writeln(z);

writeln(z,'The total number of SMILES: in active training set NsmsA=',NsmsA:4,
'  in passive training set NsmsP=',NsmsP:4,
'  in calibratuion set NsmsC=',NsmsC:4,
' Nact=',Nact:3,' NactSFk=',NactSFk:3 );
writeln(z);
// if form1.CheckBox32.Checked then
// hybrid place
if form1.CheckBox30.Checked then
writeln(z,'Hydrogen suppressed graph (HSG) is used in the model');
if form1.CheckBox29.Checked then
writeln(z,'Hydrogen filled graph (HFG) is used in the model');
if form1.CheckBox31.Checked then
writeln(z,'Graph of Atomic Orbitals (GAO) is used in the model');


if form1.CheckBox21.Checked then
writeln(z,'SMILES is used  in the model');



writeln(z,'ID is number of SA in the completed list of SAs');
Writeln(z,'N1 is the number of SMILES in active training set with SA');
writeln(z,'N2 is the number of SMILES in passive training set with SA');
writeln(z,'N3 is the number of SMILES in calibration set with SA');
writeln(z);
writeln(z,'The number of SMILES in active training set is ',NsmsA);
writeln(z,'The number of SMILES in passive training set is ',NsmsP);
writeln(z,'The number of SMILES in calibration set is ',NsmsC);
writeln(z);
writeln(z);
writeln(z,
' SAk        :',
//' CW(SAk)    :',
'        ID  :',
'        NA  :',
'        NP  :',
'        NC  :',
' DEFECT[SAk]:',
'  Active '
);

(*
' TRN_minus  :',
' TRN_plus   :',
' TRN_dR     :',
' CLB_minus  :',
' CLB_plus   :',
' CLB_dR     :',
' TST_minus  :',
' TST_plus   :',
' TST_dR     :'
);
*)
nmr:=0;
SplitDef:=0.0;
//probe:=1; // Dec12,2024 Alberto problem

for i:=1 to n_glb do
if Wstyle(CW[probe,i]) then
begin
inc(nmr);

for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]);

// Modification should be here April6,2023
// ggg

CWactive[i]:=trns[i]>LimNi;

if CWactive[i] then inc(NactiveCWs);

if not CWactive[i] then cw[1,i]:=0.0;

f2:=7; if cw[probe,i]=off then f2:=1; // formats 0.9978178 == 1.0

(*
if CW[probe,i]<>Off then write(z,colon,CW[probe,i]:12:ffd,colon,i:12,colon)
                    else write(z,colon,CW[probe,i]:12:1  ,colon,i:12,colon);
*)
// AverageQualification:=AverageQualification + qualification[i];

write(z,colon,i:12,colon);     // Dec12,2024 ID

write(z,trns[i]:12,':');
write(z,clbs[i]:12,':');
write(z,tsts[i]:12,':');

//write(z,LocalSplitQuality(train,test,global_SF_list[i]):12:5);

//CWdefect[i]:=0.0; //

if CW[probe,i]<>Off then
begin
//denominator:= (Trns[i]+tsts[i]);
//if denominator=0 then denominator:=1.0;

if tsts[i]<>0 then
begin
bbb:=abs( trns[i]/NsmsA - tsts[i]/NsmsC);

if form1.radiobutton1.checked then
begin
aaa:=abs( trns[i]/NsmsA - clbs[i]/NsmsP);
ccc:=abs( clbs[i]/NsmsP - tsts[i]/NsmsC);
end
else
begin
aaa:=0.0; ccc:=0.0;
end;

CWdefect[i]:=(aaa+bbb+ccc)/(trns[i]+clbs[i]+tsts[i]);
end
else CWdefect[i]:=1.0;

end; // <>Off

// april6,2023
// blocking of SAk

CWactive[i]:=trns[i]>LimNi;
if not CWactive[i] then
begin
CW[probe,i]:=0.0;
CWdefect[i]:=1.0;
end; // if SAk is not active

write(z,CWdefect[i]:12:4,':  ',CWactive[i]);

SplitDef:=SplitDef + CWdefect[i];

(*
soul(i,Train,N_A,N_I);
write(z,N_A:12,':');
write(z,N_I:12,':');

soul(i,calib,N_A,N_I);
write(z,N_A:12,':');
write(z,N_I:12,':');

soul(i,Test ,N_A,N_I);
write(z,N_A:12,':');
write(z,N_I:12,':');
*)
writeln(z);
// If P in test less it is not excelent...

end; // i: print list of SFk globally

Nact:=NactSFk;

Density:=NactiveCWs / N_glb;

//SplitDef:=SplitDef / Nact;

writeln(z,
'Threshold=',limNI,
' Number of SMILES Attributes(SA)=',n_glb,
' Number of active SA=',Nact
);

writeln(z); //
writeln(z,'* List of attributes which are absent in invisible training set and not blocked:');
nmr:=0;
for i:=1 to n_glb do
if (CW[probe,i]<>OFF) and (Clbs[i]=0) then
begin
inc(nmr); write(z,nmr:4,' ');
for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]); writeln(z);
end; // i
if nmr=0 then writeln(z,'Empty');

writeln(z);
writeln(z,'* List of attributes which are absent in calibration set and not blocked:');
nmr:=0;
for i:=1 to n_glb do
if (CW[probe,i]<>OFF) and (Tsts[i]=0) then
begin
inc(nmr); write(z,nmr:4,' ');
for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]); writeln(z);
end; // i
if nmr=0 then writeln(z,'Empty');
writeln(z);
writeln(z,'* List of attributes which are absent in invisible training and calibration sets and not blocked:');
nmr:=0;
for i:=1 to n_glb do
if (CW[probe,i]<>OFF) and (clbs[i]=0) and (Tsts[i]=0) then
begin
inc(nmr); write(z,nmr:4,' ');
for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]); writeln(z);
end; // i
if nmr=0 then writeln(z,'Empty');
closefile(z);
outof:
SplitInfo;

// doDefectSMILES;splitdefect[limni]:=FuncSplitDefect;
splitDefect[limni]:=SplitDef;
Nact:=NactSFk;

if SplitDef<>0 then
begin
form1.Edit35.Text:=FloatToStrF(SplitDefect[limni], FFfixed,9,2);
end; // split def <> 0

end; // SaveOptimizMatrix

procedure savesplitLV;
var f,w:text;
    nn,
    kkk,
    k,j:integer;
    r,
    rr,
    s:string;

begin
// if form1.CheckBox6.Checked then
//r:=floatToStrF( sqr(R2C),FFfixed,9,3);

s:='#TotalSetLV.txt';
  begin
   assign(w,s);
   rewrite(w);
   assign(f,form1.Edit1.Text);
   rewrite(f);
   for k:=1 to nsms do
//   if types[k]<>Reject then
    begin
(*
    showmessage
    (
    types[k]+' '+
    cas[k]+' '+
    sms[k]+' '+
    FloatTostrF(pa[k],FFfixed,9,3)
    );
*)
(*
      write(f,types[k]);
      write(w,types[k]);
      for j:=1 to length(casLV[k]) do write(f,CAS[k][j]);      write(f,' ');
      for j:=1 to length(casLV[k]) do write(w,CAS[k][j]);      write(w,' ');
*)
      r:=types[k]+cas[k];
      rr:='';
      kkk:=0;
      repeat kkk:=kkk+1;
      if r[kkk]<>' ' then rr:=rr+r[kkk]
      until kkk>=length(r);

      write(f,rr,' ');
      write(w,rr,' ');

      for j:=1 to length(sms[k])-1 do
       begin
        if sms[k][j]=reBAR then sms[k][j]:=BAR;
        write(f,sms[k][j]);
        write(w,sms[k][j]);
       end;

      if form1.CheckBox17.Checked then writeln(f,' ',trunc(pa[k])) else writeln(f,' ',pa[k]:9:3) ;
      if form1.CheckBox17.Checked then writeln(w,' ',trunc(pa[k])) else writeln(w,' ',pa[k]:9:3) ;
    end; // k

close(f);
close(w);
  end; // checkbox6 checked
end; // save split

procedure savesplit;
var f,w:text;
    nn,
    kkk,
    k,j:integer;
    r,
    rr,
    s:string;
    cri:real;
begin

LV:=LV+1;
// ggggg June 3,2024 novelty for Las Vegas algorithm
//cri:= 0.5*(R2c+R2v);
cri:=R2v;

if cri>=LVRCmax then
begin
LVRCmax:=cri;
lVbest:=LV;
end;

// if form1.CheckBox6.Checked then
r:=floatToStrF( sqr(R2C),FFfixed,9,3)+'-'+IntToStr(LV)+'('+IntToStr(LVbest)+')';

s:='model/'+IntToStr(lv)+'#TotalSet'+r+'.txt';
LVlist[LV]:=s;
  begin
   assign(w,s);
   rewrite(w);
   assign(f,form1.Edit1.Text);
   rewrite(f);

   for k:=1 to nsms do
//   if types[k]<>Reject then
    begin
(*
    showmessage
    (
    types[k]+#13+
    cas[k]+#13+
    sms[k]
    );
*)
(*
      write(f,types[k]);
      write(w,types[k]);
      for j:=1 to length(cas[k]) do write(f,CAS[k][j]);      write(f,' ');
      for j:=1 to length(cas[k]) do write(w,CAS[k][j]);      write(w,' ');
*)

      r:=types[k]+cas[k];
      rr:='';
      kkk:=0;
      repeat kkk:=kkk+1;
      if r[kkk]<>' ' then rr:=rr+r[kkk]
      until kkk>=length(r);

      write(f,rr,' ');
      write(w,rr,' ');


      for j:=1 to length(sms[k])-1 do
       begin
        if sms[k][j]=reBAR then sms[k][j]:=BAR;
        write(f,sms[k][j]);
        write(w,sms[k][j]);
       end;
      if form1.CheckBox17.Checked then writeln(f,' ',trunc(pa[k])) else writeln(f,' ',pa[k]:9:3) ;
      if form1.CheckBox17.Checked then writeln(w,' ',trunc(pa[k])) else writeln(w,' ',pa[k]:9:3) ;
    end; // k

close(f);
close(w);
  end; // checkbox6 checked
end; // save split

procedure TForm1.Button2Click(Sender: TObject); // exit from program
begin
// December 6,2022
{$I-}
reset(sym);
{$I+}
if IOResult <> 0 then halt;

closefile(sym); // october18,2022 test xyx
Halt;
end;

procedure clearPlot(x0,y0:integer);
var x,y:integer;
begin
form1.Canvas.Pen.Color:=clwhite;
//form1.Canvas.Pen.Color:=clblack;
for x:=x0-45 to x0+rx+55 do
for y:=y0+30 downto y0-ry-15 do
begin
form1.Canvas.moveto(x,y);
form1.Canvas.LineTo(x+1,y+1);
end; // y,x
end; // clearPlot

procedure opt0(fname,zname,zname2:string);
var
    z,            // output file
    f:textfile;   // input file
    mss, show     // string for messages
    //zname,        // name of output file
    //fname
    :string; // name of input file
    nt:integer;


begin

Randomize;
//Form1.Activate;

clearPlot(x10,y10);     clearPlot(x20,y20);       clearPlot(x30,y30);

//if Radiobutton1.checked then style:='1';
//if Radiobutton2.checked then style:='2';
//if Radiobutton3.checked then style:='3';
//if Radiobutton4.checked then style:='4';

level1:=True; level2:=True; level3:=True;
SMILESAk:=Form1.Edit25.text[1];

if not Form1.checkBox1.checked then begin level1:=False; end;
if not Form1.checkBox2.checked then begin level2:=False; end;
if not Form1.checkBox3.checked then begin level3:=False; end;

drawaxes;

If not model_is_loaded then
iniCWs:=True; // Random start values Of the SFk should be defined

//fname:=edit1.Text;
LoadSMILES(fname);

nt:=number_SMILES_in_SET(train);

if (nt<StrToInt(form1.Edit22.Text) ) or (nt<StrToInt(form1.Edit23.Text) ) then
begin

showmessage(
'Number of compounds in the training set is less than '+#13+
'assigned threshold. Please correct method.'+#13+
'Program will be Halted');
halt;

end; // Number compound in subtrain less than Threshold

if (StrToFloat( form1.edit20.text)<=0) or (StrToFloat( form1.edit21.text)<=0) then
begin
showmessage('Options for Dstart and/or dprecision cannot to be less or equal to zero'+#13
+'Method should be corrected. Program will be halted');
Halt;
end; // D or d <=0

if nsms>3 then
begin
form1.label8.caption:='ID: 1 - '+intToStr(nsms);
// Edit3.text:='1';
end; // nsms>3

//zname:=edit2.Text;
//if series<>'y' then LimNI:=StrToInt(form1.edit10.Text);

// ShowMessage('ENTER IN SavaOptimizMatrix');

SaveOptimizMatrix(zname,zname2);

form1.label18.Caption:='The number of active SMILES attributes is '
+IntToStr(NactSFk);

sd:=StrToFloat(form1.edit20.text);
ssd:=strToFloat(form1.edit21.text);

form1.label1.Caption:='Download SMILES from '+fname+' is finished';
// button3.Enabled:=false;
end; //opt0

procedure TForm1.Button3Click(Sender: TObject); // read from SMILES file
begin   // button3click start
Button8.Enabled:=true;
opt0(Edit1.Text,Edit2.Text,'work');

end;  // button3 click


Procedure iniMonteCarlo;
var k:integer;
begin
if n_glb<5 then
ShowMessage('Initiation of Monte Carlo: the number of SMILES attributes is less than 5');
for k:=1 to n_glb do ro[k]:=k;
end; // iniMonteCarlo

procedure MonteCarloOrder;
var n1,n2,reg,k:integer; swech:boolean;
begin
for k:=1 to n_glb do
begin

repeat
n1:=trunc(random*n_glb)+1;
n2:=trunc(random*n_glb)+1;
until n1<>n2;
reg:=ro[n1]; ro[n1]:=ro[n2]; ro[n2]:=reg;

end; // k

end; // MonteCarloOrder

procedure showdots(parol:char;var y,x:DCWPA);
Label outof;
var
     count,
     x1,y1,x2,y2,       remembercolor,
     k,x0,y0:integer;
     z0,z1,
//     mnx,mxx,
//     mny,mxy:real;

     startx,starty,
     finishx,finishy,
     c0,c1,dc0,dc1,rp:real;

begin

if show_optimiz then goto OutOf;    //October16,2024

minmax(x,mnx,mxx);
minmax(y,mny,mxy);

(*
if do_vld then
begin
showmessage
(
floattostrF(mnx,FFfixed,9,3)+ '   '+floattostrF(mxx,FFfixed,9,3)+#13+
floattostrF(mny,FFfixed,9,3)+ '   '+floattostrF(mxy,FFfixed,9,3)
);
end; // do vld
*)

if parol=Train then begin x0:=x10;y0:=y10; end;
if parol=Calib then begin x0:=x20;y0:=y20; end;
if parol=Test  then begin x0:=x30;y0:=y30; end;
if parol=Valid then begin x0:=x40;y0:=y40; end;
count:=0;

//if not form1.CheckBox17.Checked then
begin
   for k:=1 to nsms do
   if types[k]=parol then
   begin
   inc(count);

   x1:=iks  (x0,rx,minx,maxx,(x[k]-mnx)/(mxx-mnx));
   y1:=igrek(y0,ry,miny,maxy,(y[k]-mny)/(mxy-mny));

//x2:=iks  (x0,rx,minx,maxx,x[k]/mxx+1);
//y2:=igrek(y0,ry,miny,maxy,y[k]/mxy+1);

dodot(x1,y1);

(*
   form1.Canvas.MoveTo(x1,y1);
   form1.Canvas.LineTo(x1-1,y1-1);
   form1.Canvas.LineTo(x1+1,y1-1);  // "large" dots
   form1.Canvas.LineTo(x1+1,y1+1);
   form1.Canvas.LineTo(x1-1,y1+1);
   form1.Canvas.LineTo(x1-1,y1-1);
*)
//form1.Canvas.LineTo(x1,y1-2); form1.Canvas.LineTo(x1,y1+2); //"super large
//form1.Canvas.LineTo(x1-2,y1); form1.Canvas.LineTo(x1+2,y1); // dots"

//form1.Canvas.LineTo(x1  ,y1+1); //"little dots"
//form1.Canvas.LineTo(x1+1,y1+1);
//form1.Canvas.LineTo(x1+1,y1  );
//form1.Canvas.LineTo(x1  ,y1  );

   end; // k
end; // YesNo

form1.Canvas.MoveTo(x1,y1);
//form1.Canvas.LineTo(x2,y2);

outof:    // October16,2024

end; // showdots

procedure readdata( var fname:string);

label outof;
var nmr,k,j,ksms:integer;
    f:textfile;
    ok:boolean;
    d1,
    colon:char;
    mss:string;
begin // readdata

form1.edit4.Text:='0';
form1.edit5.Text:='1';
ok:=true;
assignfile(f,fname);
{$I-}
reset(f);
{$I+}
if IOResult <> 0 then
begin
if series='n' then showmessage(Fname+' not found');
if series='y' then showmessage('The scenario of calculations cannot be carried out');
stopping:=true;
ok:=False;
goto outof;
end;  // IOresult <>0

// Reading of List Global CWs(FSk)

readln(f,n_glb);

for k:=1 to n_glb do
begin
for j:=1 to MaxCharSF do read(f,Global_SF_List[k][j]);

readln(f,
d1,
CW[probe,k],
//colon,
nmr,
//colon,  { colon = ":" }
trn[k],
//colon,
clb[k],
//colon,
tst[k]);

end; // k

readln(f,nsms);

// Reading of the types,N_loc,NoSF,PA
for ksms:=1 to nsms do
begin
read(f,types[ksms]);
read(f,nuc[ksms][0]);
for k:=1 to nuc[ksms][0] do read(f,nuc[ksms,k]);readln(f,pa[ksms],CAS[ksms]);
end; // ksms

// showmessage('Readdata: '+IntToStr(ksms)+' '+cas[ksms]);

for ksms:=1 to nsms do readln(f,sms[ksms]);

closefile(f);

outof:
if ok then
      begin
      form1.label1.Caption:='OCW Data taken from '+ fname;
      if nsms>3 then
      begin
      // ???? form1.Button1.caption:='ID: 1 - '+intToStr(nsms);
      //Edit3.text:='1';
      end; // nsms>3
      end
      else form1.Label1.caption:='No Data ' +
                           fname+' is not available';
end; // readdata

procedure showStat;
Label OutOf;
var nt,nv,ne, nvld:integer;
    ft,fv,fe, fvld,
    st,sv,se, svld,
    rt,rv,re, rvld,
    mt,mv,me, mvld, // for MAE printing in STAT card

    q2t,q2c,q2v, // Q2 or Rcv on train, calib, test sets respectively
    dc0,dc1,
    dc00,dc11,
    c00,c11, // help for calculation rpred wiwout of change c0,c1,dc0,dc1
    c0,c1:real;
begin

// May4,2023
if show_optimiz then goto OutOf;

//alpha:=StrToFloat(form1.edit8.Text);

form1.label2.Font.Color:=clBlack;
form1.label3.Font.Color:=clBlack;
form1.label12.Font.Color:=clBlack;

rt:=kfkr(Train,DCW,PA,types,nt);
rv:=kfkr(Calib,DCW,PA,types,nv);
re:=kfkr(Test ,DCW,PA,types,ne);

if do_vld then rvld:=kfkr(Valid,DCW,PA,types,nvld);

ft:=Fischer_PA_c0_c1_DCW(rt,nt);
fv:=Fischer_PA_c0_c1_DCW(rv,nv);
fe:=Fischer_PA_c0_c1_DCW(re,ne);
if do_vld then fvld:= Fischer_PA_c0_c1_DCW(rvld,nvld);

c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1 );
c0c1(Calib,DCW,PA,c00,c11,dc00,dc11);
c0c1(Test ,DCW,PA,c00,c11,dc00,dc11);

st:=see(Train,c0,c1);
sv:=see(Calib,c0,c1);
se:=see(Test ,c0,c1);
if do_vld then svld:=see(valid,c0,c1);

mt:=mae(Train,c0,c1);
mv:=mae(Calib,c0,c1);
me:=mae(Test ,c0,c1);
if do_vld then mvld:=mae(valid,c0,c1);

If not DoNotQ2 then showdots(Train,DCW,PA);

form1.Edit14.Text:=
'n='+IntToStr(nt)+':'+
' R2='+FloatToStrF(sqr(rt),FFfixed,7,4)+':'+
' s=' +FloatToStrF(st,FFfixed,10,fmtsee(st))+':'+
' MAE=' +FloatToStrF(mt,FFfixed,10,fmtsee(mt))+':'+
' F=' +FloatToStrF(ft,FFfixed,5,0);

If not DoNotQ2 then showdots(calib,DCW,PA);

form1.Edit15.Text:=
'n='+IntToStr(nv)+':'+
' R2='+FloatToStrF(sqr(rv),FFfixed,7,4)+':'+
' s=' +FloatToStrF(sv,FFfixed,10,fmtsee(sv))+':'+
' MAE=' +FloatToStrF(mv,FFfixed,10,fmtsee(mv))+':'+
' F=' +FloatToStrF(fv,FFfixed,5,0);
if nv=0 then form1.Edit15.Text:='Set is empty';

If not DoNotQ2 then showdots(test ,DCW,PA);

form1.Edit16.Text:=
'n='+IntToStr(ne)+':'+
' R2='+FloatToStrF(sqr(re),FFfixed,7,4)+':'+
' s=' +FloatToStrF(se,FFfixed,10,fmtsee(se))+':'+
' MAE=' +FloatToStrF(me,FFfixed,10,fmtsee(me))+':'+
' F=' +FloatToStrF(fe,FFfixed,5,0);

if do_vld then
begin
If not DoNotQ2 then showdots(valid,DCW,PA);

form1.Edit17.Text:=
'n='+IntToStr(nvld)+':'+
' R2='+FloatToStrF(sqr(rvld),FFfixed,7,4)+':'+
' s=' +FloatToStrF(svld,FFfixed,10,fmtsee(svld))+':'+
' MAE=' +FloatToStrF(mvld,FFfixed,10,fmtsee(mvld))+':'+
' F=' +FloatToStrF(fvld,FFfixed,5,0);

end; // if do vld

//if DoNotQ2 then
begin
showdots(Train,DCW,PA);
showdots(Calib,DCW,PA);
showdots(Test ,DCW,PA);
if do_vld then showdots(valid,DCW,PA);
drawaxes;
goto outof;
end; // DoNotQ2

drawaxes;
outof:
end; // Show Statistics

procedure do_expr_calc_for_all_in_PAcalc(var c0,c1:real);
var k:integer;
begin

for k:=1 to nsms do
begin
PAcalc[k]:=c0+c1*dcw[k];
end; // k

end; // do_expr_calc_for_all_in_PAcalc


procedure optimiz(fname,ec:string);
Label interruption, halting, nextSFk, NoSAS;
var
    sum,lim,

    rss,
    rcc,
    rtt,// evolution of correlation
    sss,// nss number in TRN, ncc number in CLB, ntt number in TST
    scc,// by analogy standard error sss, scc, stt
    stt,// c0ss, c1ss, regression coefficicnet for subtarining set
    c0ss,// dc0, dc1 secondary variables
    c1ss,
    dc0,dc1:real;
    nt,nv,
    MaxSFnmr2,
    nss,// subtrain
    ncc,// calib
    ntt,// test
    it, isf :integer;

    cc0,cc1,
//    dc0,dc1,

    r1,r2:real;
    d,eps:real;
    mss:string;
    ok:boolean;
    r,     // iteration: R(TRN): R(CLB): R(TST)
    f:text;
    start_of_exchange:integer;
begin

//if form1.CheckBox7.Checked then start_of_exchange:=StrToInt(form1.Edit38.Text);

Form1.Label48.Caption:='';

// fname:=edit2.Text;

if not model_is_loaded then readdata(fname); // read SFx matrix

ok:=true;
stopping:=False;
if nsms<3 then
begin
showmessage('There is not data for calculations!');
ok:=false;
goto halting;
end; // Number SMILES (nsms) < 3

lim:=1;

// CW[0]:=1.0; // weight of SFk that is absent in the training set

doDCW;
c0c1(Train,DCW,PA,cc0,cc1,dc0,dc1);
do_expr_calc_for_all_in_PAcalc(cc0,cc1);

iniMonteCarlo;

if nsms>3 then form1.Canvas.Pen.Color :=clBlack;  ShowStat;

if series='n' then
begin
if
messageDLG(
'Monte Carlo Optimization',
mtConfirmation,
[mbOK,mbCancel],0
           )=mrCancel then
begin
ok:=False;
goto halting;
end; // mrCancel
end; // not series

DoNotQ2:=TRUE;

//maxSFnmr:=StrToInt(Form1.Edit22.text);

//showmessage('After OPTIMIZ: maxSFnmr='+intToStr(maxSFnmr2)+'.');

Nit:=strToInt(form1.edit9.text)+1; // April8,2024

form1.Button1.Enabled:=True;

for it:= 1 to Nit do
begin

//if version=3 then
if phase   = 1 then goto NoSAS;
//if version = 5 then goto NoSAS;

if it=Nit then sas:=True;

NoSAS:

form1.Label1.Caption:=
'Epoch................'+IntToStr(it)+' to '+IntToStr(Nit-1);

// showmessage(' before OPTIMIZ: maxSFnmr='+intToStr(maxSFnmr2)+'.');

MonteCarloOrder;

for isf:=1 to n_glb do
begin

if SAS and not (phase=1)then goto Halting; //this blocks phase-1 !!!

if form1.CheckBox17.Checked then
begin
doDCW;
c0c1(Train,DCW,PA,cc0,cc1,dc0,dc1);
do_expr_calc_for_all_in_PAcalc(cc0,cc1);
end; // checkBox17

//if  trns[ ro[isf] ]=0 then goto nextSFk;
//if  not CWactive[ ro[isf] ] then goto nextSFk;

 if  (Trns[ ro[isf] ]<limNi) then goto nextSFk;

form1.Canvas.Pen.Color :=clwhite;  ShowStat;

d:=sd;
eps:=d*ssd;
repeat
sum:=0;
repeat

application.ProcessMessages(); // optimiz

DoDCW;

r1:=kfkrw(Train,DCW,PA,nt);
CW[probe, ro[isf] ]:=CW[probe, ro[isf] ] + d;       doDCW;
r2:=kfkrw(Train,DCW,PA,nt);

if r2<=r1 then CW[probe, ro[isf] ]:=CW[ probe, ro[isf] ] - d;   doDCW;
// if stopping then goto halting;
sum:=sum+1; if sum>lim then goto nextSFk;
until r2<r1;
d:=-d*0.5;
until abs(d)<eps;

nextSFk:

form1.Canvas.Pen.Color :=clBlack;    ShowStat;
(*
if stopping then
begin
DoNotQ2:=False;
goto interruption;
end;
*)
end; // isf

if it>=Nit then DoNotQ2:=False;

interruption:
form1.Canvas.Pen.Color :=clBlack;    ShowStat;

//Label2.Color:=clSkyBlue;
//Label3.color:=clSkyBlue;

if stopping then goto halting;

if form1.checkbox14.checked then begin assignfile(r,ec); append(r); end;

rss:=sqr( kfkr(Train,DCW,PA,types,nss) );
rcc:=sqr( kfkr(Calib,DCW,PA,types,ncc) );
rtt:=sqr( kfkr(Test ,DCW,PA,types,ntt) );

c0c1(Train,DCW,PA,c0ss ,c1ss ,dc0 ,dc1 );

sss:=see(Train,c0ss,c1ss);
scc:=see(Calib,c0ss,c1ss);
stt:=see(Test ,c0ss,c1ss);


if form1.checkbox14.checked then
writeln(r,it:4,':',
rss:7:4,':',
rcc:7:4,':',
rtt:7:4,':',
sss:9:3,':',
scc:9:3,':',
stt:9:3);

if rss>best_r2_TRN then begin best_r2_TRN:=rss; best_it_TRN_R:=it; end;
if rtt>best_r2_TST then begin best_r2_TST:=rtt; best_it_TST_R:=it; end;

if sss<best_s_TRN then begin best_s_TRN:=sss; best_it_TRN_s:=it; end;
if stt<best_s_TST then begin best_s_TST:=stt; best_it_TST_s:=it; end;

if form1.checkbox14.checked then closefile(r);

end; //it

halting:

if ok then mss:='Optimization is completed'
      else mss:='No action has been done';

form1.Label1.caption:=mss;
//button4.Enabled :=False;
//beep;
end; // optimiz

procedure TForm1.Button4Click(Sender: TObject);
label outof, halting;
var fictivefile:string;
begin        // Tform1.button4

randomize;

label1.Caption:='Everything is ready for optimiz';

optimiz(Edit2.Text,fictivefile);     // NIT iteration of the optimiz

Button8.Enabled:=False;
end; // Button4click

function here_comma:boolean;
var x:string;
    rez:boolean;
begin
rez:=false;
x:=FloatToStr(0.1);
if x[2]=',' then rez:=true;
here_comma:=rez;
end;  // here comma decimal

procedure CheckUpStyleIICCII(var x:integer);
begin
if form1.RadioButton2.Checked then
begin
showmessage('The style 1 or 2 for Classical Scheme is unavailable');
x:=0;
end; // radiobutton2.checked = CLASSIC SCHEME
end;

procedure dobutton(index:integer);
var x:integer;
begin

case index of
34:begin
     x:=APP[1,1];
//     x:=StrToInt(form1.Button34.Caption);
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button34.Enabled:=false;
     form1.Button34.Caption:=IntToStr(x);
     form1.button34.Enabled:=True;
     APP[1,1]:=x;
  end; // 34
35:begin
     x:=APP[1,2];
//     x:=StrToInt(form1.Button35.Caption);
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button35.Enabled:=false;
     form1.Button35.Caption:=IntToStr(x);
     form1.button35.Enabled:=True;
     APP[1,2]:=x;
  end; // 35
36:begin
     x:=APP[1,3];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button36.Enabled:=false;
     form1.Button36.Caption:=IntToStr(x);
     form1.button36.Enabled:=True;
     APP[1,3]:=x;
  end; // 36
37:begin
     x:=APP[1,4];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button37.Enabled:=false;
     form1.Button37.Caption:=IntToStr(x);
     form1.button37.Enabled:=True;
     APP[1,4]:=x;
  end; // 37
38:begin
     x:=APP[1,5];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button38.Enabled:=false;
     form1.Button38.Caption:=IntToStr(x);
     form1.button38.Enabled:=True;
     APP[1,5]:=x;
  end; // 38
39:begin
     x:=APP[1,6];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button39.Enabled:=false;
     form1.Button39.Caption:=IntToStr(x);
     form1.button39.Enabled:=True;
     APP[1,6]:=x;
  end; // 39
40:begin
     x:=APP[1,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button40.Enabled:=false;
     form1.Button40.Caption:=IntToStr(x);
     form1.button40.Enabled:=True;
     APP[1,7]:=x;
  end; // 40
41:begin
     x:=APP[1,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button41.Enabled:=false;
     form1.Button41.Caption:=IntToStr(x);
     form1.button41.Enabled:=True;
     APP[1,8]:=x;
  end; // 41
42:begin
     x:=APP[2,2];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button42.Enabled:=false;
     form1.Button42.Caption:=IntToStr(x);
     form1.button42.Enabled:=True;
     APP[2,2]:=x;
  end; // 42
43:begin
     x:=APP[2,3];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button43.Enabled:=false;
     form1.Button43.Caption:=IntToStr(x);
     form1.button43.Enabled:=True;
     APP[2,3]:=x;
  end; // 43
44:begin
     x:=APP[2,4];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button44.Enabled:=false;
     form1.Button44.Caption:=IntToStr(x);
     form1.button44.Enabled:=True;
     APP[2,4]:=x;
  end; // 44
45:begin
     x:=APP[2,5];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button45.Enabled:=false;
     form1.Button45.Caption:=IntToStr(x);
     form1.button45.Enabled:=True;
     APP[2,5]:=x;
  end; // 45
46:begin
     x:=APP[2,6];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button46.Enabled:=false;
     form1.Button46.Caption:=IntToStr(x);
     form1.button46.Enabled:=True;
     APP[2,6]:=x;
  end; // 46
47:begin
     x:=APP[2,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button47.Enabled:=false;
     form1.Button47.Caption:=IntToStr(x);
     form1.button47.Enabled:=True;
     APP[2,7]:=x;
  end; // 47
48:begin
     x:=APP[2,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button48.Enabled:=false;
     form1.Button48.Caption:=IntToStr(x);
     form1.button48.Enabled:=True;
     APP[2,8]:=x;
  end; // 48
49:begin
     x:=APP[3,3];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button49.Enabled:=false;
     form1.Button49.Caption:=IntToStr(x);
     form1.button49.Enabled:=True;
     APP[3,3]:=x;
  end; // 49
55:begin
     x:=APP[3,4];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button55.Enabled:=false;
     form1.Button55.Caption:=IntToStr(x);
     form1.button55.Enabled:=True;
     APP[3,4]:=x;
  end; // 55
56:begin
     x:=APP[3,5];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button56.Enabled:=false;
     form1.Button56.Caption:=IntToStr(x);
     form1.button56.Enabled:=True;
     APP[3,5]:=x;
  end; // 56
57:begin
     x:=APP[3,6];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button57.Enabled:=false;
     form1.Button57.Caption:=IntToStr(x);
     form1.button57.Enabled:=True;
     APP[3,6]:=x;
  end; // 57
58:begin
     x:=APP[3,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button58.Enabled:=false;
     form1.Button58.Caption:=IntToStr(x);
     form1.button58.Enabled:=True;
     APP[3,7]:=x;
  end; // 58
59:begin
     x:=APP[3,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button59.Enabled:=false;
     form1.Button59.Caption:=IntToStr(x);
     form1.button59.Enabled:=True;
     APP[3,8]:=x;
  end; // 59
50:begin
     x:=APP[4,4];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button50.Enabled:=false;
     form1.Button50.Caption:=IntToStr(x);
     form1.button50.Enabled:=True;
     APP[4,4]:=x;
  end; // 50
60:begin
     x:=APP[4,5];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button60.Enabled:=false;
     form1.Button60.Caption:=IntToStr(x);
     form1.button60.Enabled:=True;
     APP[4,5]:=x;
  end; // 60
61:begin
     x:=APP[4,6];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button61.Enabled:=false;
     form1.Button61.Caption:=IntToStr(x);
     form1.button61.Enabled:=True;
     APP[4,6]:=x;
  end; // 61
62:begin
     x:=APP[4,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button62.Enabled:=false;
     form1.Button62.Caption:=IntToStr(x);
     form1.button62.Enabled:=True;
     APP[4,7]:=x;
  end; // 62
63:begin
     x:=APP[4,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button63.Enabled:=false;
     form1.Button63.Caption:=IntToStr(x);
     form1.button63.Enabled:=True;
     APP[4,8]:=x;
  end; // 62
51:begin
     x:=APP[5,5];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button51.Enabled:=false;
     form1.Button51.Caption:=IntToStr(x);
     form1.button51.Enabled:=True;
     APP[5,5]:=x;
  end; // 51
64:begin
     x:=APP[5,6];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button64.Enabled:=false;
     form1.Button64.Caption:=IntToStr(x);
     form1.button64.Enabled:=True;
     APP[5,6]:=x;
  end; // 64
65:begin
     x:=APP[5,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button65.Enabled:=false;
     form1.Button65.Caption:=IntToStr(x);
     form1.button65.Enabled:=True;
     APP[5,7]:=x;
  end; // 65
66:begin
     x:=APP[5,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button66.Enabled:=false;
     form1.Button66.Caption:=IntToStr(x);
     form1.button66.Enabled:=True;
     APP[5,8]:=x;
  end; // 66
52:begin
     x:=APP[6,6];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button52.Enabled:=false;
     form1.Button52.Caption:=IntToStr(x);
     form1.button52.Enabled:=True;
     APP[6,6]:=x;
  end; // 52
67:begin
     x:=APP[6,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button67.Enabled:=false;
     form1.Button67.Caption:=IntToStr(x);
     form1.button67.Enabled:=True;
     APP[6,7]:=x;
  end; // 67
68:begin
     x:=APP[6,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button68.Enabled:=false;
     form1.Button68.Caption:=IntToStr(x);
     form1.button68.Enabled:=True;
     APP[6,8]:=x;
  end; // 68
53:begin
     x:=APP[7,7];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button53.Enabled:=false;
     form1.Button53.Caption:=IntToStr(x);
     form1.button53.Enabled:=True;
     APP[7,7]:=x;
  end; // 53
69:begin
     x:=APP[7,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button69.Enabled:=false;
     form1.Button69.Caption:=IntToStr(x);
     form1.button69.Enabled:=True;
     APP[7,8]:=x;
  end; // 69
54:begin
     x:=APP[8,8];
     x:=x+1;
     if not (x in [0,1,2]) then x:=0;
     form1.button54.Enabled:=false;
     form1.Button54.Caption:=IntToStr(x);
     form1.button54.Enabled:=True;
     APP[8,8]:=x;
  end; // 54

71:begin
     x:=APP[8,1];
     x:=x+1;
     CheckUpStyleIICCII(x);
     if not (x in [0,1,2]) then x:=0;
     form1.button71.Enabled:=false;
     form1.Button71.Caption:=IntToStr(x);
     form1.button71.Enabled:=True;
     APP[8,1]:=x;
     IIC_style:=x;
     form1.Edit28.Text:=form1.Button71.Caption;
  end; // 71

72:begin
     x:=APP[7,1];
     x:=x+1;
     CheckUpStyleIICCII(x);
     if not (x in [0,1,2]) then x:=0;
     form1.button72.Enabled:=false;
     form1.Button72.Caption:=IntToStr(x);
     form1.button72.Enabled:=True;
     APP[7,1]:=x;
     CCI_style:=x;
     form1.Edit29.Text:=form1.Button72.Caption;
  end; // 72

75:begin            // CCCP
     x:=APP[6,1];
     x:=x+1;
     CheckUpStyleIICCII(x);
     if not (x in [0,1,2]) then x:=0;
     form1.button75.Enabled:=false;
     form1.Button75.Caption:=IntToStr(x);
     form1.button75.Enabled:=True;
     APP[6,1]:=x;
     CCI_style:=x;
     form1.Edit3.Text:=form1.Button75.Caption;
  end; // 75

////////////////////////// January 9, 2020
 end; // case
end; // dobutton(index)


procedure TForm1.FormActivate(Sender: TObject);
var s,ss:string;
    k,kk:integer;
begin

form1.Top:=20;

//setscreen;

//for k:=1 to 8 do
//for Kk:=1 to 8 do app[k,kk]:=-1;
//for k:=34 to 69 do dobutton(k);

comma:=here_comma;

//Fd :=StrToInt(form1.Edit30.text); // format DCW:12:fd
//Fp :=StrToInt(form1.Edit31.text); // format PA:12:fp

DoLine:=False;
// Do_vld:=False;

Reject:='=';
Train :='+';
Calib :='-';
Test  :='#';
Valid :='*';


//form1.Button1.Enabled:=False;

//Model_is_loaded:=False;

if not do_vld then
begin
x10:=57 ; y10:=130;      // Point of origin Plot for the Training Ser
x20:=57 ; y20:=290;      // Point of origin plot for the Test Set
x30:=57 ; y30:=450;      // Point of origin plot for the External Test Set
Rx :=157; Ry :=100;     // Size of the quadratic plots
end
else
begin
x10:= 57; y10:= 110;  // 110
x20:= 57; y20:= 220;
x30:= 57; y30:= 330;
x40:= 57; y40:= 443;
rx :=130; ry :=  60;    // 50
end; //

//s:=form1.Caption;
//ss:=s+': load METHOD to search model; SYSTEM to use model';
if Form1.caption='CORAL.SEA'
then form1.Caption:='CORAL: Please load method or make a random split';

GraphParol:=Train;

CASdelta:=1;

drawaxes;

end;

Procedure DemoDCW(zname:string);
label outof;
var
    nadj,
    numDemo:integer;
    z:textfile;
    smsfiltr,
    mss:string;
    No, mantissa,
    k,j:integer;
    NatSFk,
    DCW:real;
    ok:boolean;
begin // button5click

ok:=True;

//numDemo:=StrToInt(form1.Edit3.text); June11,2024
numDemo:=1;
if (numDemo<1) or (numDemo>nsms) then
begin
if nsms=0 then form1.label48.caption:='' //'There is not data! (DEMODCW)'
          else
begin
if (numdemo>nsms) or (numdemo<0) then
showmessage('Number of SMILES should be from (1-'+intToStr(nsms)+')');
end;
ok:=False;
goto outof;
end; // bad number

form1.Label1.Caption :='For demo choisen No. '+IntToStr(numDemo);

assignfile(z,zname);
{$I-}
rewrite(z);
{$I+}
if IOResult <> 0 then
begin
mss:='File '+ zname+': An error: record is impossible';
messageDLg(mss,mtInformation,[mbOK],0);
goto outof;
end;  // IOresult <>0

writeln(z,DotInSMILES);
writeln(z);
Writeln(z,'This file contains example of DCW-calculation');
writeln(z);

write(z,'SMILES:  ');
for j:=1 to length(sms[numDemo])-1 do write(z,sms[numDemo][j]);
writeln(z);

writeln(z,'Set (',types[numDemo],'):   training +; invisible training -; calibration #');
writeln(z,'Number of structure ',numDemo);
writeln(z,'CAS ',CAS[numDemo]);
Writeln(z,'Number of Monte Carlo optimization probe ',probe);
Writeln(z,'Threshold ',limni);


if form1.CheckBox32.Checked then
begin
if form1.CheckBox30.Checked
then writeln(z,'Hydrogen suppressed Graph (HSG) is used in the model');
if form1.CheckBox29.Checked
then writeln(z,'Hydrogen Filled Graph (HFG) is used in the model');
if form1.CheckBox31.Checked
then writeln(z,'Graph of Atomic Orbitals (GAO) is used in the model');
end; // graph

if form1.CheckBox21.Checked then
writeln(z,'SMILES is used in the model');

SMS_in_SF(SMS[numDemo],cas[numDemo],Local_SF_list,n_loc);

DCW:=off;

writeln(z);

Writeln(z,'ID is the number of SMILES attribute (SA) in global list of SA');
Writeln(z,'CW(SA) is the correlation weight for SA');
Writeln(z,'NT is the number of SA in training set');
Writeln(z,'NiT is the number of SA in invisible training set');
writeln(z,'NC is the number of SA in calibration set');
writeln(z);

writeln(z,' Structural :            :     :     :     :    ');
writeln(z,'  attribute :   CW(SA)   : ID  : NT  : NiT : NC ');
writeln(z,'    (SA)    :            :     :     :     :    ');
Writeln(z);

for k:=1 to n_loc do
begin
for j:=1 to MaxCharSF do write(z,local_SF_list[k][j]);

NatSFk:= NaturalCW(LOcal_SF_list[k],No);
mantissa:=4; if NatSFk=off then mantissa:=1;
writeln(z,':',NatSFk:12:mantissa,':',No:5,':',trns[no]:5,':',clbs[no]:5,':',tsts[no]:5);

if scheme='*' then DCW:=DCW*NatSFk else DCW:=DCW+NatSFk;
end; // k

Writeln(z);
Writeln(z,'DCW=',DCW:12:ffD);

if form1.CheckBox32.Checked then
begin

filtr(SMS[numDEMO],smsfiltr);

SMILES_in_Adj(smsfiltr,Adj,Nadj,ListOfAtom);

if (form1.CheckBox29.Checked) or (form1.CheckBox31.Checked) then
HSG_in_HFG(adj,adj2,listOfAtom,nadj);

if (form1.CheckBox31.Checked) then
HFG_in_GAO(adj,adj2,ListOfAtom,listOfAO,nadj,n_GAO);

writeln(z);
writeln(z,'The Adjacency Matrix of the molecular Graph');
writeln(z);
write(z,'        :');for k:=1 to Nadj do write(z, k:4,':');  writeln(z);
write(z,'        :');for k:=1 to Nadj do write(z,listOfAtom[k]:4,':');

writeln(z,' EC0: EC1: EC2: EC3: PT2: PT3: PT4: S2 : S3 : NNC');

for k:=1 to Nadj do
begin
write(z,listOfAtom[k]:4,k:4,':');
for j:=1 to Nadj do write(z,adj[k,j]:4,':');
write(z,ec0(adj,nadj,k):4,':');
write(z,ec1(adj,nadj,k):4,':');
write(z,ec2(adj,nadj,k):4,':');
write(z,ec3(adj,nadj,k):4,':');
write(z,pt2(adj,nadj,k):4,':');
write(z,pt3(adj,nadj,k):4,':');
write(z,pt4(adj,nadj,k):4,':');
write(z, S2(adj,nadj,k):4,':');
write(z, S3(adj,nadj,k):4,':');
write(z,NNC(adj,nadj,k):4);
writeln(z);
end; // j,k

end; // Graph

closefile(z);
outof:
if ok then form1.label1.Caption:='SEE file '+zname+ #13 +
                                 'SMILES No. '+IntToStr(NumDEMO)
      else form1.Label1.caption:='DemoDCW was not done';

end;  // DemoDCW(Edit6.text)

procedure doReBAR(var sms:string);     // december 10,2020
var k:integer;
begin
for k:=1 to length(sms) do
if sms[k]=BAR then sms[k]:=reBAR;
//sms:=sms+BCE;
end; // doreBAR(SMS)

Procedure ExternalSMILES;
var Nadj,k,j,No:integer;
    SMILES,
    fname,
    smsfiltr,
    Chana:string;
    SMS_defect,
    CW_defect,
    NatSFk,
    c0,c1,
    ep,
    dcw:real;
    f:text;
begin

If length(Form1.Edit44.Text)=0 then
begin
showmessage(Form1.Label38.Caption);
exit;
end; // there is not SMILES

Chana:='noChana';

fname:=dir+form1.Edit47.Text;

assign(f,fname);
rewrite(f);

writeln(f,DotInSMILES);
writeln(f);

Writeln(f,'This file contains an example of calculations of DCW and endpoint');
writeln(f,'for SMILES that is inserted in dialog box');

SMILES:=form1.Edit44.Text+BCE;
doReBAR(SMILES);
form1.Edit44.Text:=SMILES;       // December 10,2020

filtr(SMILES,smsfiltr);
//form1.Edit44.Text:=smsfiltr;


for j:=1 to length(SMILES)-1 do write(f,SMILES[j]);
writeln(f);

writeln(f,'Selected threshold is ',form1.edit22.text);
Writeln(f);

probe:=1;

SMS_in_SF(SMILES,Chana,Local_SF_list,n_loc);

SMS_defect:=0.0;

DCW:=0.0;
writeln(f,'SMILES attribute (SA) : Correlation Weight :   SA defect');
//writeln(f,'                      :                    ');
//Writeln(f);
for k:=1 to n_loc do
begin
write(f,'          ');
for j:=1 to MaxCharSF do write(f,local_SF_list[k][j]);

NatSFk:= NaturalCW(LOcal_SF_list[k],No);
CW_defect:=CWdefect[no];

SMS_defect:=SMS_defect + CW_defect;

// showmessage(  IntToStr(n_loc)+' '+IntToStr(k)+') '+LOcal_SF_list[k] + FloatToStrF(NatSFk,FFfixed,12,5) );

if NatSFk<>0 then write(f,':',NatSFk:20:ffp) else write(f,':',NatSFk:20:1);
write(f,':',CW_defect:12:5);
writeln(f);

DCW:=DCW+NatSFk;
end; // k

//Write(f,'-------------------------------------------');
Write(f,'-----            SMILES defect          ----');

writeln(f,SMS_defect:12:5);
Writeln(f);
Writeln(f,'2 * Average SMILESdefect =',2*AveDefectSMILES:12:5);
Writeln(f);

if SMS_defect < 2*AveDefectSMILES
then writeln(f,'This SMILES falls into Domain of applicability')
else writeln(f,'This SMILES does not fall into Domain of applicability');

writeln(f);

form1.Label39.Visible:=true;
form1.Label40.Visible:=true;
form1.Edit45.Visible:=true;
form1.Edit46.Visible:=true;

form1.Edit45.Text:=FloatToStrF(DCW,FFfixed,12,ffd);

c0:=StrToFloat(form1.edit4.text);
c1:=StrToFloat(form1.edit5.text);

EP:=c0+c1*dcw;

form1.Edit46.Text:=FloatToStrF(EP,FFfixed,12,ffp);

Writeln(f,'DCW=',DCW:12:ffd,'  Prediction for EndPoint=',EP:12:ffp);


if form1.CheckBox32.Checked then
begin
SMILES_in_Adj(smsfiltr,Adj,Nadj,ListOfAtom);

if (form1.CheckBox29.Checked) or (form1.CheckBox31.Checked) then
HSG_in_HFG(adj,adj2,listOfAtom,nadj);

if (form1.CheckBox31.Checked) then
HFG_in_GAO(adj,adj2,ListOfAtom,listOfAO,nadj,n_GAO);

writeln(f);

write(f,'    :');
for k:=1 to Nadj do write(f,listOfAtom[k]:4,':');
writeln(f,' EC0: EC1: EC2: EC3: PT2: PT3: PT4: S2 : S3 : NNC ');

for k:=1 to Nadj do
begin
write(f,listOfAtom[k]:4,':');
for j:=1 to Nadj do write(f,adj[k,j]:4,':');
write(f,ec0(adj,nadj,k):4,':');
write(f,ec1(adj,nadj,k):4,':');
write(f,ec2(adj,nadj,k):4,':');
write(f,ec3(adj,nadj,k):4,':');
write(f,pt2(adj,nadj,k):4,':');
write(f,pt3(adj,nadj,k):4,':');
write(f,pt4(adj,nadj,k):4,':');
write(f,s2 (adj,nadj,k):4,':');
write(f,s3 (adj,nadj,k):4,':');
write(f,NNC(adj,nadj,k):4);
writeln(f);

end; // j,k

end; // Graph

closefile(f);
end;  // ExternalSMILES()

procedure KRoy(var n:integer; var k,kk,r2,r02,rr02,rm2:real; var x,y:DCWPA);

var ay,ax,
    avx,avy:real;
    s1,s2,s3,s4:real;
    i:integer;
    xr,yr:DCWPA;

begin
if form1.checkbox17.Checked then exit;

//showmessage('KroyN='+inttostr(n) );

avx:=0.0;
avy:=0.0;
for i:=1 to n do
begin
//showmessage(inttostr(i)+' '+' x='+floattostrF(x[i],FFfixed,9,3)+' y='+floattostrF(y[i],FFfixed,9,3) );
avx:=avx+x[i];
avy:=avy+y[i];
end; (*averages x and y *)

avx:=avx/n;
avy:=avy/n;

s1:=0; s2:=0; s3:=0; s4:=0;
for i:=1 to n do
begin
s1:=s1 + x[i]*y[i];
s2:=s2 + sqr(y[i]);
s4:=s4 + sqr(x[i]);
end; (* s1 s2 s3 s4 *)

k :=s1/s2;
kk:=s1/s4;


for i:=1 to n do
begin
xr[i]:=k  *y[i];
yr[i]:=kk *x[i];
end; (* xr yr *)


s1:=0; s2:=0; s3:=0; s4:=0;
for i:=1 to n do
begin
ay:=(y[i]-avy);
ax:=(x[i]-avx);

s1:=s1 + ay*ax;
s2:=s2 + sqr(ay);
s3:=s3 + sqr(ax);
end; (* r2 *)

r2:=sqr( s1/sqrt(s2*s3) );

s1:=0; s2:=0; s3:=0; s4:=0;
for i:=1 to n do
begin
ay:=(y[i]-yr[i]);
ax:=(y[i]-avy);

s1:=s1 + sqr(ay);
s2:=s2 + sqr(ax);
end; (* r, r02, rr02 *)

rr02:=1-s1/s2;

s1:=0; s2:=0; s3:=0; s4:=0;
for i:=1 to n do
begin
ay:=(x[i]-xr[i]);
ax:=(x[i]-avx);

s1:=s1 + sqr(ay);
s2:=s2 + sqr(ax);
end; (* r, r02, rr02 *)

r02:=1-s1/s2;

rm2:=r2*(1-sqrt( abs(r2-r02) ));

end; (* KRoy *)


procedure do_expr_calc_for_test (var c0,c1:real; parol:char);
var k:integer;
begin
KRoyN:=0;
for k:=1 to nsms do
if types[k]=test then
begin
inc(KroyN);
KRoyX[KroyN]:=pa[k];
kroyY[KRoyN]:=c0+c1*dcw[k];
end; // types=test
end; // do_expr_calc_for_test

procedure Y_scrambling_100_10(var f:text);
const
//    Nscrambling=1000;
      NaverageR=10;
var   i,k,n1,n2:integer;
      exchange:real;
      Nscrambling:integer;

      N_TRN,
      N_CLB,
      N_TST : integer;

      Delta_TRN,
      Delta_CLB,
      Delta_TST,

      R_TRN,
      R_CLB,
      R_TST,

      R_TRNa,
      R_CLBa,
      R_TSTa : real;

      M_TRN,
      M_CLB,
      M_TST,               // M = MCC calculation
                           // R = R calculation
      M_TRNa,      // MCCs for binary classifications
      M_CLBa,
      M_TSTa : double;

      M_TRNs,
      M_CLBs,
      M_TSTs : array[1..Naverager] of double;

      R_TRNs,
      R_CLBs,
      R_TSTs : array[1..Naverager] of real;

        sensitivity,specificity,accuracy,MCC:double;
        TP,TN,FP,FN:integer;


begin
if form1.checkbox17.Checked then exit;

PA_Y_scrambling:=pacalc;

R_TRN:=sqr(kfkr(Train,pa,pacalc,types,N_TRN));
R_CLB:=sqr(kfkr(Calib,pa,pacalc,types,N_CLB));
R_TST:=sqr(kfkr(Test ,pa,pacalc,types,N_TST));

if classification
then
begin
 do_classification(Train,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);
 M_TRN:=MCC;
 do_classification(Calib,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);
 M_CLB:=MCC;
 do_classification(Test ,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);
 M_TST:=MCC;

R_TRN:=M_TRN;
R_CLB:=M_CLB;
R_TST:=M_TST;


end;

// Nscrambling:=N_TRN;
Nscrambling:=10000;

R_TRNa:=0.0;
R_CLBa:=0.0;
R_TSTa:=0.0;

M_TRNa:=0.0;
M_CLBa:=0.0;
M_TSTa:=0.0;


writeln(f);
writeln(f,'Y-randomization TEST: ',Nscrambling:4,' permutations for each average');
writeln(f,'Y-randomization TEST can be useful for regression models,');
writeln(f,'but for classification models the test is probably unuseful.');
writeln(f);
write  (f,'                                 :');
write  (f,'  A     :');
write  (f,'  P     :');
writeln(f,'  C ');

write  (f,'                                 :');
write  (f,N_TRN:8,':');
write  (f,N_CLB:8,':');
writeln(f,N_TST:8    );

(**)
if classification
then
begin
write  (f,'                                 :');
write  (f,M_TRN:8:4,':');
write  (f,M_CLB:8:4,':');
writeln(f,M_TST:8:4    );
end
else
(**)
begin
write  (f,'                                 :');
write  (f,R_TRN:8:4,':');
write  (f,R_CLB:8:4,':');
writeln(f,R_TST:8:4    );
end;


for i:=1 to NaverageR do
begin

pacalc:=PA_Y_scrambling;

for k:=1 to Nscrambling do
begin
repeat
n1:=trunc(random*nsms)+1;
n2:=trunc(random*nsms)+1;
until n1<>n2;
exchange:=PAcalc[n1]; PAcalc[n1]:=PAcalc[n2]; PAcalc[n2]:=exchange;
end; // 100 shifting

if classification
then
begin
do_classification(Train,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);
M_TRNs[i]:=abs(MCC);
do_classification(Calib,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);
M_CLBs[i]:=abs(MCC);
do_classification(Test ,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);
M_TSTs[i]:=abs(MCC);
end
else
begin
R_TRNs[i]:=sqr(kfkr(Train,pa,pacalc,types,N_TRN));
R_CLBs[i]:=sqr(kfkr(Calib,pa,pacalc,types,N_CLB));
R_TSTs[i]:=sqr(kfkr(Test ,pa,pacalc,types,N_TST));
end;

(**)
if classification
then
begin
write  (f,i:33,':');
write  (f,abs(M_TRNs[i]):8:4,':');
write  (f,abs(M_CLBs[i]):8:4,':');
writeln(f,abs(M_TSTs[i]):8:4    );
end
else
(**)
begin
write  (f,i:33,':');
write  (f,R_TRNs[i]:8:4,':');
write  (f,R_CLBs[i]:8:4,':');
writeln(f,R_TSTs[i]:8:4    );
end;

(**)
if classification
then
begin
M_TRNa:=M_TRNa + M_TRNs[i];
M_CLBa:=M_CLBa + M_CLBs[i];
M_TSTa:=M_TSTa + M_TSTs[i];
end
else
(**)
begin
R_TRNa:=R_TRNa + R_TRNs[i];
R_CLBa:=R_CLBa + R_CLBs[i];
R_TSTa:=R_TSTa + R_TSTs[i];
end;

end; // i, Naverager

(**)
if classification
then
begin
M_TRNa:=M_TRNa/Naverager;
M_CLBa:=M_CLBa/Naverager;
M_TSTa:=M_TSTa/Naverager;
end
else
(**)
begin
R_TRNa:=R_TRNa/Naverager;
R_CLBa:=R_CLBa/Naverager;
R_TSTa:=R_TSTa/Naverager;
end;

(**)
if classification
then
begin
write  (f,'MCCr2, i.e. average randomized   :');
write  (f,abs(M_TRNa):8:4,':');
write  (f,abs(M_CLBa):8:4,':');
writeln(f,abs(M_TSTa):8:4    );
end
else
(**)
begin
write  (f,'Rr2, i.e. average randomized R   :');
write  (f,R_TRNa:8:4,':');
write  (f,R_CLBa:8:4,':');
writeln(f,R_TSTa:8:4    );
end;

(**)
if classification
then
begin
write  (f,'   CRp2=R*sqrt(R2-Rr2) [1]  MCC  :');
write  (f,sqrt(M_TRN)*sqrt(abs(M_TRN-M_TRNa)):8:4,':');
write  (f,sqrt(M_CLB)*sqrt(abs(M_CLB-M_CLBa)):8:4,':');
writeln(f,sqrt(M_TST)*sqrt(abs(M_TST-M_TSTa)):8:4,':');
end
else
(**)
begin
write  (f,'   CRp2=R*sqrt(R2-Rr2) [1]       :');
write  (f,sqrt(R_TRN)*sqrt(abs(R_TRN-R_TRNa)):8:4,':');
write  (f,sqrt(R_CLB)*sqrt(abs(R_CLB-R_CLBa)):8:4,':');
writeln(f,sqrt(R_TST)*sqrt(abs(R_TST-R_TSTa)):8:4,':');
end;

writeln(f);
writeln(f,' CRp2 should be greater 0.5 [1]');
writeln(f);
writeln(f,'REFERENCE for Y-scrambling');
writeln(f,'[1] P.K. Ojha, K. Roy, Comparative QSARs for antimalarial endochins:');
writeln(f,'    Importance of descriptor-thinning and noise reduction prior to');
writeln(f,'    feature selection, Chemometr. Intell. Lab. 109 (2011) 146-161');


end; // Y-scrambling


procedure stringStandard(var sms,msg:string;ExcessSF:char);

var k,fin,rez:integer;
    s:string;
begin

if (MaxSMILESlength2<25) or (MaxSMILESlength2>MaxSMILESlength) then
MaxSMILESlength2:=50;

if length(sms)<MaxSMILESlength2 then fin:=length(sms) else fin:=MaxSMILESlength2;
if length(sms)=MaxSMILESLength2 then rez:=fin+1 else rez:=fin;
fin:=rez;
s:='';for k:=1 to fin-1 do s:=s+sms[k];
msg:=s;
if length(msg)<MaxSMILESlength2 then
repeat msg:=msg+' '; until length(msg)>=MaxSMILESlength2;

end; // StringStandard


function mark(k:integer):CWsname; // i.e. 12 chars
var rez:CWsname;
begin
(*
if (PAcalc[k]>=middle01) and (pa01[k]>middle01) then rez:='       TP    ';
if (PAcalc[k]>=middle01) and (pa01[k]<middle01) then rez:='       FP    ';
if (PAcalc[k]<=middle01) and (pa01[k]<middle01) then rez:='       TN    ';
if (PAcalc[k]<=middle01) and (pa01[k]>middle01) then rez:='       FN    ';
*)
if (PAcalc[k]>=middle01) then if (pa01[k]>middle01) then rez:='       TP    '
                                                    else rez:='       FP    ';
if (PAcalc[k]<=middle01) then if (pa01[k]<middle01) then rez:='       TN    '
                                                    else rez:='       FN    ';
mark:=rez;
end; // mark - TP, TN, FP, FN

Procedure show_class(var z:text; parole:char);
var     sensitivity,specificity,accuracy,MCC:double;
        TP,TN,FP,FN:integer;
        s:string;
begin
// Writeln(z);
if parole=train then S:='Active Train ';
if parole=calib then s:='Passive Train';
if parole=test  then s:='Calibration  ';
if parole=Valid then s:='Validation   ';

do_classification(parole,sensitivity,specificity,accuracy,MCC,TP,TN,FP,FN);

if
(s='Active Train ') or
(s='Validation   ')
then

begin

writeln(z,
'Set          ',
':  Sens  ',
':  Spec  ',
':  Acc   ',
':  MCC   ',
':  TN ',
':  TP ',
':  FP ',
':  FN ',
':  All');
end;

writeln(z,s,
':',sensitivity:8:4,
':',specificity:8:4,
':',accuracy:8:4,
':',MCC:8:4,
':',TP:5,
':',TN:5,
':',FP:5,
':',FN:5,
':',TP+TN+FP+FN:5);

(**
writeln(z,'TP=',TP:5,' TN=',TN:5,' FP=',FP:5,' FN=',FN:5,' N=',TP+TN+FP+FN:5);
writeln(z,'Sensitivity=',sensitivity:7:4);
writeln(z,'Specificity=',specificity:7:4);
//writeln(z,'CCR        =',(sensitivity+specificity)*0.5:7:4);
writeln(z,'Accuracy   =',accuracy:7:4);
writeln(z,'MCC        =',MCC:7:4);
(**)

//writeln(z);

end; // show classification

procedure Q2F1Q2F2Q2F3(var c0,c1,q2f1,q2f2,q2f3:real);
var
       k:integer;
       rez, // November18,2024 q2f1-3 should be more zero or at least equal zero
       aveTRN,
       aveCLB : real;
       f1_1,
       f1_2,
       f2_2,
       f3_2 : real;
       Nclb,
       Ntrn: integer;
begin
if form1.checkbox17.Checked then exit;

q2f1:=0; q2f2:=0; q2f3:=0; // exit;   // October21, 2022
(*
showmessage
(
'C0='+
floatToStrF(c0, FFfixed, 9,4) +
'  C1='+
floatToStrF(c1, FFfixed, 9,4)
);
*)

       aveTRN:=0.0;
       aveCLB:=0.0;

       Nclb:=0;
       Ntrn:=0;

       for k:=1 to nsms do
       begin
       if types[k]=test  then begin aveCLB:=aveCLB + pa[k]; inc(Nclb); end;
       if (types[k]=train) or (types[k]=calib)
                         then begin aveTRN:=aveTRN + pa[k]; inc(Ntrn); end;
       end; // k


       aveCLB:=aveCLB / Nclb;
       aveTRN:=aveTRN / Ntrn;

       f1_1:=0.0;
       f1_2:=0.0;
       f2_2:=0.0;
       f3_2:=0.0;

       for k:=1 to nsms do
       begin
          if types[k]=test then
                              begin
                              f1_1:=f1_1 + sqr( pa[k]-(c0+c1*dcw[k]) );
                              f1_2:=f1_2 + sqr( pa[k]- aveTRN );
                              f2_2:=f2_2 + sqr( pa[k]- aveCLB );
                              end;
            if (types[k]=train) or (types[k]=calib)
                           then
                              begin
                              f3_2:=f3_2 + sqr( pa[k]- aveTRN );
                              end;
       end; // k

       rez:= 1.0 - f1_1/f1_2;
       if rez<0.01 then rez:=0.0;
       q2f1:=rez;

       rez:= 1.0 - f1_1/f2_2;
       if rez<0.01 then rez:=0.0;
       q2f2:=rez;

       rez:= 1.0 - ( f1_1/Nclb ) / ( f3_2/Ntrn );
       if rez<0.01 then rez:=0.0;
       q2f3:=rez;

end; // q2f1 q2f2 q2f3


Procedure MDL(Zname:string;YesNo:char);

var CS0,CS1, CC0,CC1, CT0, CT1 : real;


function excessSF(k:integer):char;
Label outof;
var j:integer;
    rez:char;
begin
rez:='#';
for j:=1 to nuc[k][0] do
if trn[ nuc[k][j] ]=0 then
begin rez:='?'; goto outof; end;
outof:
excessSF:=rez;
end; // excessSF

function nunac(sms,chana:string; var nSFtotal:integer):integer;
var k,No,sum:integer;
    NatSFk:real;
begin
SMS_in_SF(SMS,chana,Local_SF_list,n_loc);
nSFtotal:=n_loc;
sum:=0;
for k:=1 to n_loc do
begin
NatSFk:= NaturalCW(LOcal_SF_list[k],No);
if trn[no]<limNI then inc(sum);
end; // k
nunac:=sum;
end; // nun number of unactive SFk in given SMILES not in a set


label outof;
var z:textfile;
    mss:string;
    ntot, // number of SFk in Given SMILIS
    k,j,
    nt,nv,ne,nccc:integer;
    seet, seev, seee,
    st,sv,se,    MAE_TRN, MAE_CLB, MAE_TST, // MAE = mean absolute error
    rt,rv,re,
    q2t5,q2c5,q2v5, // January 25, 2022 q2 five-fold
    q2t ,q2c ,q2v , // Rcv on train, calib, test respectively
    ft,fv,fe,
    mdl,expcal,
    z0,z1,
    dc00,dc11,  // help for calculation rpred without changes
    c00,c11,    // of the c0,c1,dc0,dc1
    k1,k2,      // slope in the expr-calc plot
    dc0,dc1,

    c0,c1:real;
    c:char;
    password:array[1..3] of char;
    ok:boolean;
    txt:string;
    maxSFnmr2,
    r:integer;

    Rm2Copy,
    rez1,rez2,
    r2,r02,rr02,kk,kkk:real;

    start,maxim,Tstar:integer; // Oct 6, 2016
                               // Problem with DCW(T*,N*) printing
    q2f1,
    q2f2,
    q2f3: real; // N. Chrico, P. Grammatica  J. Chem. Inf. Model 2011,   51, 2320-2335
    SMSdef:real; // SMILES defect October 12, 2020
    x:real; // January 25, 2022  for  "nblk/Nall":9:3
begin

DoDCW;

z0:=StrToFloat(form1.edit4.Text);
z1:=StrToFloat(form1.edit5.Text);

txt:='C0='+form1.edit4.text+#13+
     'C1='+form1.edit5.text+#13+
     'Definition of them';

// r:=messageDlg(txt,mtConfirmation,[mbYes,mbNo],0);

// if r=mrYes then
if yesno='y' then
begin
c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1);
form1.edit4.Text:=FloatToStrF(c0,FFfixed,12,7);
form1.edit5.Text:=FloatToStrF(c1,FFfixed,12,7);
goto outof;
end; // r=mrYes

ok:=true;

if nsms<3 then
begin
if yesno='y' then form1.label48.caption:='There is not data! (MDL)';
ok:=False;
goto outof;
end; // Number SMILES<3

// zname:=Edit7.Text;

assignfile(z,zname);
{$I-}
rewrite(z);
{$I+}
if IOResult <> 0 then
begin
mss:='File '+ zname+': An error: record is impossible';
messageDLg(mss,mtInformation,[mbOK],0);
goto outof;
end;  // IOresult <>0

rt:=kfkr(Train,DCW,PA,types,nt);
rv:=kfkr(Calib,DCW,PA,types,nv);
re:=kfkr(Test ,DCW,PA,types,ne);

ft:=Fischer_PA_c0_c1_DCW(rt,nt);
fv:=Fischer_PA_c0_c1_DCW(rv,nv);
fe:=Fischer_PA_c0_c1_DCW(re,ne);

c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1  );  CS0:=c0; CS1:=c1;
c0c1(Calib,DCW,PA,cc0,cc1,dc00,dc11 );  CC0:=CC0;CC1:=CC1;
c0c1(Test ,DCW,PA,c00,c11,dc00,dc11 );  CT0:=c00;CT1:=c11;

//if r=mrNO then
if yesno='n' then
begin
c0:=z0;
c1:=z1;
end; // r=mrNo

st:=see(Train,c0,c1);
sv:=see(Calib,c0,c1);
se:=see(Test ,c0,c1);

MAE_TRN:=MAE(Train,c0,c1);
MAE_CLB:=MAE(Calib,c0,c1);
MAE_TST:=MAE(Test ,c0,c1);


q2t:=q2(train,DCW,PA,c0,c1);
q2c:=q2(calib,DCW,PA,c0,c1);
q2v:=q2(test ,DCW,PA,c0,c1);

q2t5:=RGindex(train,DCW,PA);
q2c5:=RGindex(calib,DCW,PA);
q2v5:=RGindex(test ,DCW,PA);

writeln(z,
'This file contains experimental and calculated values of the endpoint for visible sets');
writeln(z); //

writeln(z);

if form1.CheckBox30.Checked then
writeln(z,'Hydrogen suppressed graph (HSG) is used in the model');
if form1.CheckBox29.Checked then
writeln(z,'Hydrogen filled graph (HFG) is used in the model');
if form1.CheckBox31.Checked then
writeln(z,'Graph of Atomic Orbitals (GAO) is used in the model');
Writeln(z);

if form1.CheckBox21.Checked then
writeln(z,'SMILES is used in the model');

writeln(z);

writeln(z,'Data from SMILES-file (',form1.edit1.text,')');
writeln(z,'Threshold=',LimNI);
writeln(z,'The number of active SMILES attributes (ASA) =',NactSFk);
writeln(z);

if form1.CheckBox26.Checked then
begin
writeln(z,'Index of ideality of correlation (IIC) has been involved');
writeln(z,'for the Monte Carlo optimization, IIC-weight =',dKweight:7:4,')' );
writeln(z,'IIC style is ',IIC_Style );
writeln(z);
end;

if form1.CheckBox7.Checked then
begin
writeln(z,'Correlation Intensity Index (CII) has been involved');
writeln(z,'for the Monte Carlo optimization, CII-weight =',dCweight:7:4,')' );
writeln(z,'CII style is ',CCI_Style );
writeln(z);
end;

if form1.radioButton1.checked
then writeln(z,'CORRELATION BALANCE is used')
else writeln(z,'CLASSIC SCHEME is used (i.e. optimization is carried out without iTRN)');

writeln(z);

If form1.checkbox1.Checked then writeln(z,'Sk are used');
If form1.checkbox2.Checked then writeln(z,'SSk are used');
If form1.checkbox3.Checked then writeln(z,'SSSk are used');
If form1.checkbox25.Checked then writeln(z,'BOND is used');
If form1.checkbox22.Checked then writeln(z,'NOSP is used');
If form1.checkbox23.Checked then writeln(z,'HALO is used');
If form1.checkbox27.Checked then writeln(z,'HARD is used');

writeln(z);

If form1.checkbox9.Checked  then  writeln(z,'e0 (vertex degree) are used');
If form1.checkbox28.Checked then  writeln(z,'e1 (Morgans connectivity of first order) are used');
If form1.checkbox18.Checked then  writeln(z,'e2 (Morgans connectivity of second order) are used');
If form1.checkbox10.Checked then  writeln(z,'e3 (Morgans connectivity of third order) are used');
If form1.checkbox6.Checked  then  writeln(z,'p2 (Paths of length 2) are used');
If form1.checkbox12.Checked then  writeln(z,'p3 (Paths of length 3) are used');
If form1.checkbox36.Checked then  writeln(z,'p4 (Paths of length 4) are used');
If form1.checkbox13.Checked then  writeln(z,'s2 (valence shells of radius 2) are used');
If form1.checkbox37.Checked then  writeln(z,'s3 (valence shells of radius 3) are used');
If form1.checkbox20.Checked then  writeln(z,'nn (nearest neghbors codes) are used');

writeln(z);

If form1.checkbox65.Checked  then  writeln(z,'e1-e0 are used');
If form1.checkbox63.Checked  then  writeln(z,'e2-e0 are used');
If form1.checkbox60.Checked  then  writeln(z,'e3-e0 are used');
If form1.checkbox58.Checked  then  writeln(z,'p2-e0 are used');
If form1.checkbox61.Checked  then  writeln(z,'p3-e0 are used');
If form1.checkbox66.Checked  then  writeln(z,'p4-e0 are used');
If form1.checkbox62.Checked  then  writeln(z,'s2-e0 are used');
If form1.checkbox67.Checked  then  writeln(z,'s3-e0 are used');
If form1.checkbox64.Checked  then  writeln(z,'nn-e0 are used');

If form1.checkbox73.Checked  then  writeln(z,'e2-e1 are used');
If form1.checkbox70.Checked  then  writeln(z,'e3-e1 are used');
If form1.checkbox68.Checked  then  writeln(z,'p2-e1 are used');
If form1.checkbox71.Checked  then  writeln(z,'p3-e1 are used');
If form1.checkbox76.Checked  then  writeln(z,'p4-e1 are used');
If form1.checkbox72.Checked  then  writeln(z,'s2-e1 are used');
If form1.checkbox77.Checked  then  writeln(z,'s3-e1 are used');
If form1.checkbox74.Checked  then  writeln(z,'nn-e1 are used');

If form1.checkbox80.Checked  then  writeln(z,'e3-e2 are used');
If form1.checkbox78.Checked  then  writeln(z,'p2-e2 are used');
If form1.checkbox81.Checked  then  writeln(z,'p3-e2 are used');
If form1.checkbox86.Checked  then  writeln(z,'p4-e2 are used');
If form1.checkbox82.Checked  then  writeln(z,'s2-e2 are used');
If form1.checkbox87.Checked  then  writeln(z,'s3-e2 are used');
If form1.checkbox84.Checked  then  writeln(z,'nn-e2 are used');

If form1.checkbox88.Checked  then  writeln(z,'p2-e3 are used');
If form1.checkbox91.Checked  then  writeln(z,'p3-e3 are used');
If form1.checkbox96.Checked  then  writeln(z,'p4-e3 are used');
If form1.checkbox92.Checked  then  writeln(z,'s2-e3 are used');
If form1.checkbox97.Checked  then  writeln(z,'s3-e3 are used');
If form1.checkbox94.Checked  then  writeln(z,'nn-e3 are used');

If form1.checkbox101.Checked then  writeln(z,'p3-p2 are used');
If form1.checkbox106.Checked then  writeln(z,'p4-p2 are used');
If form1.checkbox102.Checked then  writeln(z,'s2-p2 are used');
If form1.checkbox107.Checked then  writeln(z,'s3-p2 are used');
If form1.checkbox104.Checked then  writeln(z,'nn-p2 are used');

If form1.checkbox116.Checked then  writeln(z,'p4-p3 are used');
If form1.checkbox112.Checked then  writeln(z,'s2-p3 are used');
If form1.checkbox117.Checked then  writeln(z,'s3-p3 are used');
If form1.checkbox114.Checked then  writeln(z,'nn-p3 are used');

If form1.checkbox122.Checked then  writeln(z,'s2-p4 are used');
If form1.checkbox127.Checked then  writeln(z,'s3-p4 are used');
If form1.checkbox124.Checked then  writeln(z,'nn-p4 are used');

If form1.checkbox137.Checked then  writeln(z,'s3-s2 are used');
If form1.checkbox134.Checked then  writeln(z,'nn-s2 are used');

If form1.checkbox54.Checked  then  writeln(z,'nn-s3 are used');

////////////////////////////////////////// December 5, 2019

If form1.checkbox69.Checked  then  writeln(z,'e1+e0 are used');
If form1.checkbox79.Checked  then  writeln(z,'e2+e0 are used');
If form1.checkbox89.Checked  then  writeln(z,'e3+e0 are used');
If form1.checkbox99.Checked  then  writeln(z,'p2+e0 are used');
If form1.checkbox109.Checked then  writeln(z,'p3+e0 are used');
If form1.checkbox119.Checked then  writeln(z,'p4+e0 are used');
If form1.checkbox129.Checked then  writeln(z,'s2+e0 are used');
If form1.checkbox49.Checked  then  writeln(z,'s3+e0 are used');
If form1.checkbox39.Checked  then  writeln(z,'nn+e0 are used');

If form1.checkbox85.Checked  then  writeln(z,'e2+e1 are used');
If form1.checkbox95.Checked  then  writeln(z,'e3+e1 are used');
If form1.checkbox105.Checked then  writeln(z,'p2+e1 are used');
If form1.checkbox115.Checked then  writeln(z,'p3+e1 are used');
If form1.checkbox125.Checked then  writeln(z,'p4+e1 are used');
If form1.checkbox135.Checked then  writeln(z,'s2+e1 are used');
If form1.checkbox55.Checked  then  writeln(z,'s3+e1 are used');
If form1.checkbox45.Checked  then  writeln(z,'nn+e1 are used');

If form1.checkbox93.Checked  then  writeln(z,'e3+e2 are used');
If form1.checkbox103.Checked then  writeln(z,'p2+e2 are used');
If form1.checkbox113.Checked then  writeln(z,'p3+e2 are used');
If form1.checkbox123.Checked then  writeln(z,'p4+e2 are used');
If form1.checkbox133.Checked then  writeln(z,'s2+e2 are used');
If form1.checkbox53.Checked  then  writeln(z,'s3+e2 are used');
If form1.checkbox43.Checked  then  writeln(z,'nn+e2 are used');

If form1.checkbox100.Checked then  writeln(z,'p2+e3 are used');
If form1.checkbox110.Checked then  writeln(z,'p3+e3 are used');
If form1.checkbox120.Checked then  writeln(z,'p4+e3 are used');
If form1.checkbox130.Checked then  writeln(z,'s2+e3 are used');
If form1.checkbox50.Checked  then  writeln(z,'s3+e3 are used');
If form1.checkbox40.Checked  then  writeln(z,'nn+e3 are used');

If form1.checkbox108.Checked then  writeln(z,'p3+p2 are used');
If form1.checkbox118.Checked then  writeln(z,'p4+p2 are used');
If form1.checkbox128.Checked then  writeln(z,'s2+p2 are used');
If form1.checkbox48.Checked  then  writeln(z,'s3+p2 are used');
If form1.checkbox38.Checked  then  writeln(z,'nn+p2 are used');

If form1.checkbox121.Checked then  writeln(z,'p4+p3 are used');
If form1.checkbox131.Checked then  writeln(z,'s2+p3 are used');
If form1.checkbox51.Checked  then  writeln(z,'s3+p3 are used');
If form1.checkbox41.Checked  then  writeln(z,'nn+p3 are used');

If form1.checkbox136.Checked then  writeln(z,'s2+p4 are used');
If form1.checkbox56.Checked  then  writeln(z,'s3+p4 are used');
If form1.checkbox46.Checked  then  writeln(z,'nn+p4 are used');

If form1.checkbox52.Checked  then  writeln(z,'s3+s2 are used');
If form1.checkbox42.Checked  then  writeln(z,'nn+s2 are used');

If form1.checkbox47.Checked  then  writeln(z,'nn+s3 are used');
If form1.checkbox132.Checked  then  writeln(z,'Chaos-index is used');

If form1.checkbox4.Checked  then  writeln(z,'Seven-member rings are used');
If form1.checkbox19.Checked then  writeln(z,'Six-member rings are used');
If form1.checkbox16.Checked then  writeln(z,'Five-member rings are used');
If form1.checkbox8.Checked  then  writeln(z,'Four-member rings are used');
If form1.checkbox5.Checked  then  writeln(z,'Three-member rings are used');




writeln(z,DotInSMILES);
writeln(z);
writeln(z,'IMPORTANT: In the case of classic scheme W%=N101/Nall, otherwise W%=N111/Nall');
writeln(z,'Percent of ASA with presence in all sets (W%) =',form1.edit36.text);
writeln(z);
//writeln(z,'Split Quality = ',Form1.edit35.Text);
writeln(z,'Defect of Split = ',Form1.edit35.text);
writeln(z);
writeln(z,'Intercept (c0) and slope (c1) calculated for each set individually:');

writeln(z,'Training set   : c0=',CS0:10:5,' c1=',CS1:10:5);
if not form1.RadioButton2.checked then
writeln(z,'InvTraining set: c0=',CC0:10:5,' c1=',CC1:10:5);
writeln(z,'Calibration set: c0=',CT0:10:5,' c1=',CT1:10:5);

if (z1<>1) and (z0<>0) then        // if z1<>1.0 then Rm2 will be calculated wrong!!!
begin
c0:=z0;
c1:=z1;
end; // z0 and z1 => c0 and c1

if limNI<0 then LimNI:=StrToInt(form1.Edit39.text);


writeln(z);
writeln(z,'Slope and intesept calculated with training set give the model:');
writeln(z);

start:=StrToInt(form1.Edit22.Text);
maxim:=StrToInt(form1.Edit23.Text);

if start=maxim then Tstar:=start else Tstar:=LimNI;

Writeln(z,'%%%');
writeln(z,'Endpoint =',c0:12:7,' (',chr(177),dc0:10:7,') + ',
c1:12:7,' (',chr(177),dc1:10:7,') * DCW(',Tstar,',',strToInt(form1.edit9.text), ')');
// Writeln(z,'%%%');
if not classification then
begin
writeln(z);
writeln(z,'Statistical characteristics of the model:');
writeln(z);
writeln(z,'N is the number of compounds in the set;');
writeln(z,'R is correlation coefficient;');
writeln(z,'Q is cross-validated correlation coefficient;');
writeln(z,'CCC is concordance correlation coefficient;');
writeln(z,'IIC is index of ideality of correlation;');
writeln(z,'CII is correlation intensity index;');
writeln(z,'s is standard error of estimation;');
writeln(z,'MAE is mean absolute error;');
writeln(z,'F is Fischer F-ratio');
writeln(z);
Writeln(z,'Blk is the number of SMILES attributes in given SMILES, which are blocked');
Writeln(z,'All is the number of all SMILES attributes in given SMILES string');
end;

do_expr_calc_for_test(c0,c1,test);
do_expr_calc_for_all_in_PAcalc(c0,c1);
//if not classification then
Y_scrambling_100_10(z);
(**)

txt:=
' C0='+ FloatToStrF(c0,FFfixed,12,7)+#13+
' C1='+ FloatToStrF(c1,FFfixed,12,7);

// showmessage(txt);
(**)


Kroy(KRoyN,kk,kkk,r2,r02,rr02,rm2,KRoyY,KRoyX);

if not classification then
begin
writeln(z);
writeln(z,'External validation characteristics for the model taken from');
Writeln(z,'REFERNCES');
writeln(z,'[1] Golbraikh A., Tropsha A. J.Mol.Graph.Model. 20(2002)269; // R02, k,kk');
writeln(z,'[2] Roy P.P., Roy K. Chem. Biol. Drug Des. 73(2009) 442; // Rm2');
writeln(z,'[3] PK Ojha,I Mitra, RN Das,K Roy,Chemometr Intell Lab 107(2011)194-205');
writeln(z,'    // Average of Rm2 and absolute difference Rm2(x,y)-Rm2(y,x)');
writeln(z,'    // x,y are experimental and predicted values of endpoint');
writeln(z,'[4] I-Kuei Lin, L. A concordance correlation coefficient to');
writeln(z,'    evaluate reproducibility (1989) Biometrics, 45 (1), 255-268.');
writeln(z,'[5] Toropova, A.P.,Toropov, A.A. The index of ideality of correlation:');
writeln(z,'    A criterion of predictability of QSAR models for skin permeability?');
writeln(z,'    (2017) Science of the Total Environment, 586, 466-472.');

writeln(z);
writeln(z,'The range of endpoint:');
writeln(z,'Min=',min01:5:1,' Max=',max01:5:1,' Middle=',Middle01:5:1);
writeln(z);

writeln(z,'n           =',KroyN:8);
writeln(z,'r2          =',r2:10:4);
writeln(z,'r02         =',r02:10:4);
writeln(z,'rr02        =',rr02:10:4);
rez1:=(r2-r02)/r2;
rez2:=(r2-rr02)/r2;
writeln(z,'(r2-r02)/r2 =',rez1:10:4,' should be < 0.1 [1]');
writeln(z,'(r2-rr02)/r2=',rez2:10:4,' should be < 0.1 [1]');
writeln(z,'k           =',kk:10:4, ' should be 0.85 <  k < 1.15 [1]');
writeln(z,'kk          =',kkk:10:4,' should be 0.85 < kk < 1.15 [1]');
writeln(z,'Rm2(test)   =',Rm2:10:4,' should be > 0.5 [2]');
writeln(z);
end;
rm2copy:=rm2;

Kroy(KRoyN,kk,kkk,r2,r02,rr02,rm2,KRoyX,KRoyY);

if not classification then
begin
writeln(z,'n           =',KroyN:8);
writeln(z,'r2          =',r2:10:4);
writeln(z,'r02         =',r02:10:4);
writeln(z,'rr02        =',rr02:10:4);
rez1:=(r2-r02)/r2;
rez2:=(r2-rr02)/r2;
writeln(z,'(r2-r02)/r2 =',rez1:10:4,' should be < 0.1 [1]');
writeln(z,'(r2-rr02)/r2=',rez2:10:4,' should be < 0.1 [1]');
writeln(z,'k           =',kk:10:4, ' should be 0.85 <  k < 1.15 [1]');
writeln(z,'kk          =',kkk:10:4,' should be 0.85 < kk < 1.15 [1]');
writeln(z,'R*m2(test)  =',Rm2:10:4,' should be > 0.5 [2]');
writeln(z);
writeln(z,'Average Rm2 =',0.5*(rm2copy+rm2):7:4,' should be larger 0.5 [3]');
writeln(z,'Delta Rm2 =',abs(rm2copy-rm2):7:4,' should be lower 0.2 [3]');
end;

if classification then
begin
Writeln(z,'%%%1');
// DoDCW;

for k:=1 to nsms do
begin
PA01[k]:=PA[k];
PAcalc[k]:=c0+c1*DCW[k];
end; // k
show_class(z,Train);
if form1.radioButton1.checked then show_class(z,Calib);
show_class(z,Test );
end; // classification


if not classification then
begin
writeln(z,'$$$');

write(z,  '        :',
          '  n :',
          '  R2   :',
          '  CCC  :',
          '  IIC  :',
          '  CII  :',
          '  Q2   :',
          ' CCCP  :',
          '  Q2F1 :',
          '  Q2F2 :',
          '  Q2F3 :',
          ' <Rm2> :',
          '  RMSE  :',
          '    MAE :',
          '  F     '
          );

writeln(z);

writeln(z,'A:':9,nt:4,':',
          sqr(rt ):7:4,':',
          ccc(train,dcw,pa,types,nccc):7:4,':',
          IIC_autonom(train,c0,c1,dcw,pa,types):7:4,':',
          CCI(train,c0,c1,dcw,pa,types):7:4,':',
          (q2t):7:4,':',
          (q2t5):7:4,':',
          '       :',
          '       :',
          '       :',
          '       :',
          st:8:fmtsee(st),':',
          MAE_TRN:8:fmtsee(MAE_TRN),':',
          ft:9:0);

if not form1.RadioButton2.checked then
writeln(z,'P:':9,nv:4,':',
          sqr(rv):7:4,':',
          ccc(calib,dcw,pa,types,nccc):7:4,':',
          IIC_autonom(calib,c0,c1,dcw,pa,types):7:4,':',
          CCI(calib,c0,c1,dcw,pa,types):7:4,':',
          (q2c):7:4,':',
          (q2c5):7:4,':',
          '       :',
          '       :',
          '       :',
          '       :',
          sv:8:fmtsee(sv),':',
          MAE_CLB:8:fmtsee(MAE_CLB),':',
          fv:9:0);

          Q2F1Q2F2Q2F3(c0,c1,q2f1,q2f2,q2f3);

writeln(z,'C:':9,ne:4,':',
          sqr(re):7:4,':',
          ccc(test ,dcw,pa,types,nccc):7:4,':',
          IIC_autonom(test ,c0,c1,dcw,pa,types):7:4,':',
          CCI(test ,c0,c1,dcw,pa,types):7:4,':',
          (q2v):7:4,':',
          (q2v5):7:4,':',
          (q2f1):7:4,':',
          (q2f2):7:4,':',
          (q2f3):7:4,':',
          0.5*(rm2copy+rm2):7:4,':',
          se:8:fmtsee(se),':',
          MAE_TST:8:fmtsee(MAE_TST),':',
          fe:9:0);

// start of Table preparetion
end; // not classification

Writeln(z);
writeln(z,'Active Training set (A) indicated by    +;');
if not form1.RadioButton2.checked then
writeln(z,'Passive training set (P) indicated by -;');
writeln(z,'Calibration set (C) indicated by #');
writeln(z);
//writeln(z,'******',middle01:7:2);
//writeln(z);
if form1.RadioButton2.Checked then
begin
writeln(z,'C l a s s i c a l   s c h e m e :');
writeln(z,'    Training set - Calibration set');
end
else
begin
writeln(z,'B a l a n c e   o f   c o r r e l a t i o n s :');
writeln(z,'    Active training set - Passive training set - Calibration set');
end; //

writeln(z);

// October 12, 2020
////////////////////////////////////////////// begin
doDefectSMILES;

AveDefectSMILES:=0.0;
for k:=1 to nsms do
begin
AveDefectSMILES:=AveDefectSMILES + DefectSMILES[k];
end; // k

AveDefectSMILES:=AveDefectSMILES / nsms;
////////////////////////////////////////////// end

writeln(z,'DefectSMILES should be less than value of [ 2 x Average Defect SMILES ] = ',AveDefectSMILES * 2.0:12:4);

writeln(z,' AD = Applicability domain');
writeln(z);

write(z,' :');

mss:='SMILES     '; StringStandard(mss,mss,'*');

write(z,mss,':');

mss:='DCW('+IntToStr(limni)+','+form1.Edit9.Text+')';

repeat
mss:=' '+mss;
until length(mss)>=12;

write(z,mss,':');
write(z,'        Expr:');
write(z,'        Calc:');
write(z,'   Expr-Calc:');
write(z,'DefectSMILES:');
write(z,'     AD      :');

//write(z,' Blk/All :');
write(z,' ID ');
writeln(z);


seet:=0.0;
seev:=0.0;
password[1]:=Train;
password[2]:=Calib;
password[3]:=Test;

for j:=1 to 3 do
for k:=1 to nsms do
if types[k]=password[j] then
begin
write(z,types[k],':');

c:=excessSF(k);

StringStandard(sms[k],mss,c);
write(z,mss,':');
write(z,DCW[k]:12:ffd,':');


if classification then write(z,PA01[k]:12:0,':')
                  else write(z,PA[k]:12:ffp,':');

//write(z,PA[k]:12:mantissaPA,':');


mdl:=c0+c1*dcw[k];

if classification then write(z,PAcalc[k]:12:ffp,':')
                  else write(z,mdl:12:ffp,':');

expcal:=pa[k]-mdl;

if classification then write(z,mark(k),':')
                  else write(z,expcal:12:ffp,':');


SMSdef:=SMILES_defect(SMS[k],CAS[k],local_SF_list);
write(z,SMSdef:12:4,':');
if SMSdef>2*AveDefectSMILES then write(z,'     NO      :')
                            else write(z,'     YES     :');


// write(z,mdl:12:ffp,':');

// write(z,expcal:12:mantissaPA,':');

//x:=nunac(sms[k],chana[k],ntot);

//write(z,ntot:9,':');
write(z,CAS[k]);

writeln(z);

end; // k

closefile(z);

outof:

if ok then
begin
form1.edit4.Text:=FloatToStrF(c0,FFfixed,12,7);
form1.edit5.Text:=FloatToStrF(c1,FFfixed,12,7);
end; // ok

If series='n' then
begin
if ok then form1.Label1.Caption :='See file '+zname
      else form1.Label1.Caption :='No actions were done';
end // series=no
else
begin
form1.Label1.Caption :='THE CALCULATION IS COMPLETED';
end;
end; // MDL(Edit7.text)


procedure TForm1.Button5Click(Sender: TObject);
begin // button5click

MDL(edit7.Text,'y');
MDL(edit7.Text,'n');

end;  // button5click


// here building up splits TRN CLB TST VLD
procedure TForm1.Button6Click(Sender: TObject);
begin
form2.show;
form2.Label6.Caption:='1.';
form2.Label7.Caption:='2.';
form2.Label8.Caption:='3.';
form2.Left:=470;
end;


procedure TForm1.RadioButton1Click(Sender: TObject);
begin
style:='1';
end;

procedure TForm1.RadioButton2Click(Sender: TObject);
begin
style:='2';
end;

procedure TForm1.RadioButton3Click(Sender: TObject);
begin
style:='3';
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
Radiobutton1.Checked :=True;
end;

procedure TForm1.Button7Click(Sender: TObject);
begin
if graphParol=Calib then
if form1.Edit15.Text='Set is empty' then
begin
showmessage('The calibration set is empty. Analysis of the calibration set is nonsence');
exit;
end; // set is empty
//showCAS(DCW,PA);

if switch012=0 then showCAS (graphparol,PA,DCW); // March14,2024
if switch012=1 then showCAS (graphparol,PA,DCW); // July 3, 2015
if switch012=2 then showCAS2(graphparol,PA,DCW); // March14,2024

end;

function randomnum(lim:integer):integer;
begin
randomnum:=trunc(1+lim*random);
end; // randomnum

procedure shift;
var n1,n2,k,limShift,j:integer;
    f:text;
    smsk,
    fl:string;
    x:char;
begin

if nsms=0 then begin showmessage('No data!'); exit; end;

limShift:=100;
k:=0;
repeat inc(k);
repeat
n1:=randomnum(nsms); if n1>nsms then showmessage('Shiftn1n2>NSMILES');
n2:=randomnum(nsms); if n2>nsms then showmessage('Shiftn1n2>NSMILES');
until (n1<>n2) and (types[n1]<>Reject) and  (types[n2]<>Reject);
x:=types[n1]; types[n1]:=types[n2]; types[n2]:=x;
until k>limShift;

fl:=form1.Edit17.Text;
assignfile(f,fl);
rewrite(f);
for k:=1 to nsms do
begin
smsk:='';
smsk:=smsk+types[k];

for j:=1 to length(cas[k]) do
smsk:=smsk+cas[k][j];

smsk:=smsk+' ';

for j:=1 to length(sms[k])-1 do
smsk:=smsk+sms[k][j];

smsk:=smsk+' ';
smsk:=smsk+FloatToStrF(PA[k],FFfixed,12,7);
writeln(f,smsk);
end; // k
closefile(f);
showmessage(fl+' is ready');
end; // shifting of the +,-, and ; = do not touch

procedure TForm1.Button9Click(Sender: TObject);
begin

//RedGreen := Not RedGreen;

switch012:=switch012+1;
if not (switch012 in [0,1,2]) then switch012:=0;

if switch012=0 then
begin
form1.Button9.Caption:='Marker-0';
redGreen:=False;
end; // switch012=0

if switch012=1 then
begin
form1.Button9.Caption:='Marker-1';
RedGreen:=True;
end;

if switch012=2 then
begin
form1.Button9.Caption:='Marker-2';
RedGreen:=True;
end; // switch012=2

end;

procedure TForm1.RadioButton4Click(Sender: TObject);
begin
Style:='4';
end;


procedure step1;
begin
form1.Label34.Visible:=true;
form1.Edit39.Visible:=true;
form1.button11.visible:=true;

form1.button14.visible:=False;
form1.button16.visible:=False;
form1.button17.visible:=False;
form1.Edit19.Visible:=False;


form1.label34.Caption:='Define threshold and press Continue';

end; //step1

procedure step2;
begin

form1.Label9.Visible:=true;
form1.Label10.Visible:=true;
form1.Edit4.Visible:=true;
form1.Edit5.Visible:=true;

end; //step 2

procedure LimSLimN;
begin;

SMILESAk:='S'; exit;

(*
SMILESAk:=Form1.edit25.text[1];

if SMILESAk='S' then
begin
SMILESAk:='N';
form1.Edit25.Text:='N';
form1.Button19.Caption:='LimN';
// application.ProcessMessages();
exit;
end;

if SMILESAk='N' then
begin
SMILESAk:='S';
form1.Edit25.Text:='S';
form1.Button19.Caption:='LimS';
// application.ProcessMessages();
exit;
end;
*)
end; // limSLimN

function is_this_float(var s:string):boolean;
label outof;
var k,j:integer;       rez:boolean;
decimal:char;
begin

if comma then decimal:=',' else decimal:='.';

for j:=1 to length(s) do
if (s[j]='.') or (s[j]=',') then s[j]:=decimal;

rez:=true;
for k:=1 to length(s) do
if not (s[k] in ['0','1','2','3','4','5','6','7','8','9',decimal]) then
begin
rez:=false;
goto outof;
end; // not digit and point

outof:
is_this_float:=rez;
end; // is this float?

procedure change(var s:string);
begin
if not is_this_float(s) then
      begin
      showmessage('File '+form1.Edit19.Text+' is not correct'+ #13 +
                  'The program will be halted');
                  halt;
      end; // not float
end; // change s

procedure SwitchShowCAS(x:char);
var rez:boolean;
begin
if x='0' then rez:=False else rez:=True;

form1.Button7.Enabled:=rez;  form1.Button9.Enabled:=rez;
form1.Button30.Enabled:=rez;
form1.Button31.Enabled:=rez;
form1.Button32.Enabled:=rez;

end; // SwitchShowCas(0 off 1 on)

procedure permession_to_work;
begin

form1.Button6.Visible:=false;
form1.Button15.Visible:=false;

if
(
form1.CheckBox4.Checked or
form1.CheckBox19.Checked or
form1.CheckBox16.Checked or
form1.CheckBox8.Checked or
form1.CheckBox5.Checked
)
and
form1.CheckBox31.Checked
then
begin
showmessage(
'It is impossible to use GAO together with cycles. ');
//halt;
form1.CheckBox4.Checked:=False;
form1.CheckBox19.Checked:=False;
form1.CheckBox16.Checked:=False;
form1.CheckBox8.Checked:=False;
form1.CheckBox5.Checked:=False;

end; // GAO and Cycles
end; // permission to work

procedure loadmethod;
var r:text;   s:string;   b:char;
    k,kk:integer; // January 9, 2020 atoms pairs proportions app[k,kk]
begin

SwitchShowCAS('0');

assignfile(r,form1.Edit19.Text);
{$I-}
reset(r);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+form1.Edit19.Text+' is not found');
exit;
end;  // IOresult <>0

form1.Label34.Visible:=false;
form1.Label9.Visible:=false;
form1.Label10.Visible:=false;
form1.Label38.Visible:=false;
form1.Label41.Visible:=false;
form1.Label39.Visible:=false;
form1.Label40.Visible:=false;


form1.Edit39.Visible:=false;
form1.Edit4.Visible:=false;
form1.Edit5.Visible:=false;
form1.Edit44.Visible:=false;
form1.Button33.Visible:=False;
form1.Edit47.Visible:=false;
form1.Edit45.Visible:=false;
form1.Edit46.Visible:=false;
form1.Edit48.Visible:=false;
form1.Edit49.Visible:=false;

// form1.Button10.Visible:=false;
form1.Button11.Visible:=false;
form1.Button12.Visible:=false;
form1.Button27.Visible:=false;

      readln(r,s);form1.edit1.text:=s; // smiles file

      if version=3 then Form1.Edit1.Text:='#TrainingSet.txt';

      readln(r,s);form1.edit9.text:=s; change(s);form1.edit9.text:=s;// nit
      readln(r,s);form1.edit3.text:=s; change(s);form1.edit3.text:=s;// ID for Demo DCW
      readln(r,s);form1.edit20.text:=s; change(s);form1.edit20.text:=s;// sd
      readln(r,s);form1.edit21.text:=s; change(s);form1.edit21.text:=s;// ssd
      readln(r,s);form1.edit10.text:=s; change(s);form1.edit10.text:=s;// IICweight
      readln(r,s);form1.edit22.text:=s; change(s);form1.edit22.text:=s;// limN start
      readln(r,s);form1.edit23.text:=s; change(s);form1.edit23.text:=s;// limN finish

      if StrToInt(form1.Edit23.text) > MaxThreshold then
      begin
      form1.Edit23.Text:=intToStr(maxthreshold);
      showmessage('The maximum for the threshold is '+form1.Edit23.Text);
      end; //

if StrToInt( form1.edit22.text)> StrToInt(  form1.edit22.text) then
begin
showmessage('Definition of range for threshold is wrong. Program will be halted');
halt;
end; // Threshold: Start>Finish

      readln(r,s);form1.edit24.text:=s; change(s);// N probes
      readln(r,s);form1.edit19.text:=s; // file name method

      readln(r,b);form1.checkBox1.checked:=(b='y'); //     -s
      readln(r,b);form1.checkBox2.checked:=(b='y'); //     -ss
      readln(r,b);form1.checkBox3.checked:=(b='y'); //     -sss
      readln(r,b);form1.checkBox4.checked:=(b='y'); //     + (
      readln(r,b);form1.checkBox5.checked:=(b='y'); //     + =
      readln(r,b);form1.checkBox6.checked:=(b='y'); //     + #
      readln(r,b);form1.checkBox7.checked:=(b='y'); //     + Index of correlation confidence Nov 1, 2019

//      if form1.CheckBox7.Checked then form1.Edit38.Enabled:=True
//                                 else form1.Edit38.Enabled:=False;

      readln(r,b);form1.checkBox8.checked:=(b='y'); //     + Oxygen
      readln(r,b);form1.checkBox9.checked:=(b='y'); //     + Cl
      readln(r,b);form1.checkBox10.checked:=(b='y'); //    + Br
      readln(r,b);form1.checkBox11.checked:=(b='y'); //    + F
      readln(r,b);form1.checkBox12.checked:=(b='y'); //    + S
      readln(r,b);form1.checkBox13.checked:=(b='y'); //    + P
      readln(r,b);form1.checkBox14.checked:=(b='y'); //    + 1
      readln(r,b);form1.checkBox15.checked:=(b='y'); //    + 2
      readln(r,b);form1.checkBox16.checked:=(b='y'); //    + 3
      readln(r,b);form1.checkBox17.checked:=(b='y'); //    + CLASSIFICATION

      Classification:=False;
      if form1.CheckBox17.Checked then classification:=True;

      readln(r,b);form1.checkBox18.checked:=(b='y'); //    + 5
      readln(r,b);form1.checkBox19.checked:=(b='y'); //    + Csp3
      readln(r,b);form1.checkBox20.checked:=(b='y'); //    + csp2
      readln(r,b);form1.checkBox21.checked:=(b='y'); //    + SMILES
      readln(r,b);form1.checkBox22.checked:=(b='y'); //    + \/ cis-trans
      readln(r,b);form1.checkBox23.checked:=(b='y'); //    + @@,@ R,L chirality
      readln(r,b);form1.checkBox24.checked:=(b='y'); //    + S-Ideality Nov15, 2017

      readln(r,b);form1.checkBox25.checked:=(b='y'); //    + BOND Index

      readln(r,b);form1.checkBox26.checked:=(b='y'); // IIC Nov23 2016
//                  form1.checkBox26.checked:=False;

if (form1.CheckBox26.Checked) then   // Index of Ideality of correlation
begin                                //
form1.Label53.Visible:=true;         // weight
form1.Label54.Visible:=true;         // dK
form1.Edit10.Visible:=True;          // dK value in text format
form1.Edit28.Visible:=True;          // IIC-style
form1.button71.Visible:=True;

end
else
begin
form1.Label53.Visible:=false;
form1.Label54.Visible:=false;
form1.Edit10.Visible:=false;
form1.Edit28.Visible:=False;          // IIC-style
form1.button71.Visible:=False;
end;

if (form1.CheckBox7.Checked) then   // Correlation Contradiction Index (CCI)
begin                                //
form1.Label79.Visible:=true;         // weight
form1.Label80.Visible:=true;         // dK
form1.Edit38.Visible:=True;          // dK value in text format
form1.Edit29.Visible:=True;          // CCI-style
form1.button72.Visible:=True;
end
else
begin
form1.Label79.Visible:=false;
form1.Label80.Visible:=false;
form1.Edit38.Visible:=false;
form1.Edit29.Visible:=False;          // CCI-style
form1.button72.Visible:=False;
end;

if (form1.Chk1.Checked) then   // CCCP
begin                                //
form1.Label90.Visible:=true;
form1.Label91.Visible:=true;
form1.Edit3.Visible:=True;
form1.button75.Visible:=True;
form1.Edit53.Visible:=True;
//form1.Edit54.Visible:=True;   // percetexchange October11,2024
end
else
begin
form1.Label90.Visible:=false;
form1.Label91.Visible:=false;
form1.Edit3.Visible:=false;
form1.button75.Visible:=False;
form1.Edit53.Visible:=False;
//form1.Edit54.Visible:=False;  // percetexchange October11,2024
end;



      readln(r,b);form1.checkBox27.checked:=(b='y'); //    O'
      readln(r,b);form1.checkBox28.checked:=(b='y'); //    S'
      readln(r,b);form1.checkBox29.checked:=(b='y'); //    P'
      readln(r,b);form1.checkBox30.checked:=(b='y'); //    F'
      readln(r,b);form1.checkBox31.checked:=(b='y'); //    Cl'

      readln(r,b);form1.checkBox36.checked:=(b='y'); //    pt4      June 8, 2018
      readln(r,b);form1.checkBox37.checked:=(b='y'); //    sv3

      readln(r,b);form1.checkBox32.checked:=(b='y'); //    GRAPH

      readln(r,b);authomat:=(b='y');                 //    + Selfcontrol/interact
if authomat then form1.button23.Caption:='Selfcontrol'
            else form1.button23.Caption:='Interactive';
      readln(r,b);save_all_CWs:=(b='y');               //    save all or act SFk

      //if save_all_CWs then form1.Button20.Caption:='Save ALL CWs'
      //          else form1.Button20.Caption:='Save ACT CWs';

      readln(r,b);form1.Radiobutton2.Checked:=(b='y'); // yes= (TC):t
                                                       // no = (T)(C):t

if form1.radiobutton2.Checked then   // Classic scheme
begin                                //
//form1.Label36.Visible:=false;        // dC
form1.Edit42.Visible:=false;         // dC digits
form1.Edit54.Visible:=False;     // October15,2024
form1.Label37.Visible:=false;        // dR
form1.Label44.Visible:=false;        // [dR] weight
//form1.Label45.Visible:=false;        // weight [dC]
form1.Edit43.Visible:=false;         // dR digits
                                     //
form1.Label16.Visible:=false;        // weight [dK]
form1.Label47.Visible:=false;        // dK
form1.Edit31.Visible:=false;         // dK digits

(*
form1.CheckBox7.Checked:=False; // alternation of training sets is impossible Jan 16, 2018
form1.Label57.Visible:=False;
form1.Label58.Visible:=False;
form1.Edit38.Visible:=False;
*)                                     //
//form1.checkBox24.checked:=False;     // ideal C1,C1'
//form1.checkBox26.checked:=False;     // ideal k,k'

end
else
begin
form1.RadioButton1.Checked:=true;
//form1.Label36.Visible:=true;
//form1.Edit42.Visible:=true;
form1.Label37.Visible:=true;
form1.Label44.Visible:=true;
//form1.Label45.Visible:=True;
form1.Edit43.Visible:=true;

//form1.Label16.Visible:=True;
//form1.Label47.Visible:=True;
//form1.Edit31.Visible:=True;

//form1.checkBox24.Visible:=True;
//form1.checkBox26.Visible:=True;

end;

      readln(r,scheme);                                // * mult + add
(*
      if scheme='+' then form1.button15.caption:='Adding'
                    else form1.button15.caption:='Multiply';
*)
      if scheme='+' then off:=0.0 else off:=1.0;

      readln(r,b);PAmodify:=(b='y');


      if PAmodify then form1.Edit18.Text:='PA->lg(1/PA)'
                  else form1.Edit18.Text:='PA->PA';
      readln(r,b);if b='S' then form1.edit25.text:='S'
                           else form1.Edit25.text:='S'; // application.ProcessMessages();

      limSlimN;
      limSlimN;

      form1.label34.Caption:='"'+form1.button19.caption;
      //form1.label15.Caption:=form1.button19.caption;

      readln(r,s);form1.edit26.text:=s;  change(s);form1.edit26.text:=s;//duplicats



      readln(r,s);form1.edit27.text:=s;  change(s);form1.edit27.text:=s;

      readln(r,s);form1.edit28.text:=s;  change(s);form1.edit28.text:=s;// September 8,2020
      IIC_Style:=StrToInt( form1.edit28.text );
      APP[8,1]:=IIC_Style;
      form1.Button71.Caption:=IntToStr(IIC_Style);

      readln(r,s);form1.edit29.text:=s;  change(s);form1.edit29.text:=s;
      CCI_Style:=StrToInt( form1.edit29.text );
      APP[7,1]:=CCI_Style;
      form1.Button72.Caption:=IntToStr(CCI_Style);

      readln(r,s);form1.edit30.text:=s;  change(s);form1.edit30.text:=s;// DCW:f1:f2

     if StrToInt(form1.Edit30.Text)=0 then
      begin
      form1.CheckBox33.checked:=False;
      form1.CheckBox34.checked:=False;
      form1.CheckBox35.checked:=False;
      end; // 0

      if StrToInt(form1.Edit30.Text)=1 then
      begin
      form1.CheckBox33.checked:=True;
      form1.CheckBox34.checked:=False;
      form1.CheckBox35.checked:=False;
      end; // 1

      if StrToInt(form1.Edit30.Text)=10 then
      begin
      form1.CheckBox33.checked:=False;
      form1.CheckBox34.checked:=True;
      form1.CheckBox35.checked:=False;
      end; // 10

      if StrToInt(form1.Edit30.Text)=100 then
      begin
      form1.CheckBox33.checked:=False;
      form1.CheckBox34.checked:=False;
      form1.CheckBox35.checked:=True;
      end; // 100

      if StrToInt(form1.Edit30.Text)=11 then
      begin
      form1.CheckBox33.checked:=True;
      form1.CheckBox34.checked:=True;
      form1.CheckBox35.checked:=False;
      end; // 11

      if StrToInt(form1.Edit30.Text)=101 then
      begin
      form1.CheckBox33.checked:=True;
      form1.CheckBox34.checked:=False;
      form1.CheckBox35.checked:=True;
      end; // 101

      if StrToInt(form1.Edit30.Text)=110 then
      begin
      form1.CheckBox33.checked:=False;
      form1.CheckBox34.checked:=True;
      form1.CheckBox35.checked:=True;
      end; // 110

      if StrToInt(form1.Edit30.Text)=111 then
      begin
      form1.CheckBox33.checked:=True;
      form1.CheckBox34.checked:=True;
      form1.CheckBox35.checked:=True;
      end; // 111

      readln(r,s);form1.edit31.text:=s;  change(s);form1.edit31.text:=s;

      readln(r,s);form1.edit38.text:=s;  change(s);form1.edit38.text:=s;
      readln(r,s);form1.edit39.text:=s;

      if s='0' then s:='1';

      change(s);form1.edit39.text:=s;
      readln(r,s);form1.Edit42.Text:=s;  change(s);form1.edit42.text:=s;// dCweight concelled Nov1, 2019
      readln(r,s);form1.Edit43.Text:=s;  change(s);form1.edit43.text:=s;// dRweight

            // June 20, 2018  save

Readln(r,b); form1.checkBox38.checked :=(b='y'); // p2 nn
Readln(r,b); form1.checkBox39.checked :=(b='y'); //

Readln(r,b); form1.checkBox40.checked :=(b='y'); //
Readln(r,b); form1.checkBox41.checked :=(b='y'); //
Readln(r,b); form1.checkBox42.checked :=(b='y'); //
Readln(r,b); form1.checkBox43.checked :=(b='y'); //
Readln(r,b); form1.checkBox44.checked :=(b='y'); //
Readln(r,b); form1.checkBox45.checked :=(b='y'); //
Readln(r,b); form1.checkBox46.checked :=(b='y'); //
Readln(r,b); form1.checkBox47.checked :=(b='y'); //
Readln(r,b); form1.checkBox48.checked :=(b='y'); //
Readln(r,b); form1.checkBox49.checked :=(b='y'); //
Readln(r,b); form1.checkBox50.checked :=(b='y'); //

Readln(r,b); form1.checkBox51.checked :=(b='y'); //
Readln(r,b); form1.checkBox52.checked :=(b='y'); //
Readln(r,b); form1.checkBox53.checked :=(b='y'); //
Readln(r,b); form1.checkBox54.checked :=(b='y'); //
Readln(r,b); form1.checkBox55.checked :=(b='y'); //
Readln(r,b); form1.checkBox56.checked :=(b='y'); //
Readln(r,b); form1.checkBox57.checked :=(b='y'); //
Readln(r,b); form1.checkBox58.checked :=(b='y'); //
Readln(r,b); form1.checkBox59.checked :=(b='y'); //
Readln(r,b); form1.checkBox60.checked :=(b='y'); //

Readln(r,b); form1.checkBox61.checked :=(b='y'); //
Readln(r,b); form1.checkBox62.checked :=(b='y'); //
Readln(r,b); form1.checkBox63.checked :=(b='y'); //
Readln(r,b); form1.checkBox64.checked :=(b='y'); //
Readln(r,b); form1.checkBox65.checked :=(b='y'); //
Readln(r,b); form1.checkBox66.checked :=(b='y'); //
Readln(r,b); form1.checkBox67.checked :=(b='y'); //
Readln(r,b); form1.checkBox68.checked :=(b='y'); //
Readln(r,b); form1.checkBox69.checked :=(b='y'); //
Readln(r,b); form1.checkBox70.checked :=(b='y'); //

Readln(r,b); form1.checkBox71.checked :=(b='y'); //
Readln(r,b); form1.checkBox72.checked :=(b='y'); //
Readln(r,b); form1.checkBox73.checked :=(b='y'); //
Readln(r,b); form1.checkBox74.checked :=(b='y'); //
Readln(r,b); form1.checkBox75.checked :=(b='y'); //
Readln(r,b); form1.checkBox76.checked :=(b='y'); //
Readln(r,b); form1.checkBox77.checked :=(b='y'); //
Readln(r,b); form1.checkBox78.checked :=(b='y'); //
Readln(r,b); form1.checkBox79.checked :=(b='y'); //
Readln(r,b); form1.checkBox80.checked :=(b='y'); //

Readln(r,b); form1.checkBox81.checked :=(b='y'); //
Readln(r,b); form1.checkBox82.checked :=(b='y'); //
Readln(r,b); form1.checkBox83.checked :=(b='y'); //
Readln(r,b); form1.checkBox84.checked :=(b='y'); //
Readln(r,b); form1.checkBox85.checked :=(b='y'); //
Readln(r,b); form1.checkBox86.checked :=(b='y'); //
Readln(r,b); form1.checkBox87.checked :=(b='y'); //
Readln(r,b); form1.checkBox88.checked :=(b='y'); //
Readln(r,b); form1.checkBox89.checked :=(b='y'); //
Readln(r,b); form1.checkBox90.checked :=(b='y'); //

Readln(r,b); form1.checkBox91.checked :=(b='y'); //
Readln(r,b); form1.checkBox92.checked :=(b='y'); //
Readln(r,b); form1.checkBox93.checked :=(b='y'); //
Readln(r,b); form1.checkBox94.checked :=(b='y'); //
Readln(r,b); form1.checkBox95.checked :=(b='y'); //
Readln(r,b); form1.checkBox96.checked :=(b='y'); //
Readln(r,b); form1.checkBox97.checked :=(b='y'); //
Readln(r,b); form1.checkBox98.checked :=(b='y'); //
Readln(r,b); form1.checkBox99.checked :=(b='y'); //
Readln(r,b); form1.checkBox100.checked :=(b='y'); //

Readln(r,b); form1.checkBox101.checked :=(b='y'); //
Readln(r,b); form1.checkBox102.checked :=(b='y'); //
Readln(r,b); form1.checkBox103.checked :=(b='y'); //
Readln(r,b); form1.checkBox104.checked :=(b='y'); //
Readln(r,b); form1.checkBox105.checked :=(b='y'); //
Readln(r,b); form1.checkBox106.checked :=(b='y'); //
Readln(r,b); form1.checkBox107.checked :=(b='y'); //
Readln(r,b); form1.checkBox108.checked :=(b='y'); //
Readln(r,b); form1.checkBox109.checked :=(b='y'); //
Readln(r,b); form1.checkBox110.checked :=(b='y'); //

Readln(r,b); form1.checkBox111.checked :=(b='y'); //
Readln(r,b); form1.checkBox112.checked :=(b='y'); //
Readln(r,b); form1.checkBox113.checked :=(b='y'); //
Readln(r,b); form1.checkBox114.checked :=(b='y'); //
Readln(r,b); form1.checkBox115.checked :=(b='y'); //
Readln(r,b); form1.checkBox116.checked :=(b='y'); //
Readln(r,b); form1.checkBox117.checked :=(b='y'); //
Readln(r,b); form1.checkBox118.checked :=(b='y'); //
Readln(r,b); form1.checkBox119.checked :=(b='y'); //
Readln(r,b); form1.checkBox120.checked :=(b='y'); //

Readln(r,b); form1.checkBox121.checked :=(b='y'); //
Readln(r,b); form1.checkBox122.checked :=(b='y'); //
Readln(r,b); form1.checkBox123.checked :=(b='y'); //
Readln(r,b); form1.checkBox124.checked :=(b='y'); //
Readln(r,b); form1.checkBox125.checked :=(b='y'); //
Readln(r,b); form1.checkBox126.checked :=(b='y'); //
Readln(r,b); form1.checkBox127.checked :=(b='y'); //
Readln(r,b); form1.checkBox128.checked :=(b='y'); //
Readln(r,b); form1.checkBox129.checked :=(b='y'); //
Readln(r,b); form1.checkBox130.checked :=(b='y'); //

Readln(r,b); form1.checkBox131.checked :=(b='y'); //
Readln(r,b); form1.checkBox132.checked :=(b='y'); //
Readln(r,b); form1.checkBox133.checked :=(b='y'); //
Readln(r,b); form1.checkBox134.checked :=(b='y'); //
Readln(r,b); form1.checkBox135.checked :=(b='y'); //
Readln(r,b); form1.checkBox136.checked :=(b='y'); //
Readln(r,b); form1.checkBox137.checked :=(b='y'); //

for k:=1 to 8 do
for kk:=1 to 8 do readln(r,app[k,kk]);

Readln(r,b); form1.chk1.checked :=(b='y'); // january4,2024

if form1.chk1.Checked then
begin
      CCCP_Style:=StrToInt( form1.edit3.text );
      APP[6,1]:=CCCP_Style;
      form1.Button75.Caption:=IntToStr(CCCP_Style);
      form1.Label90.Visible:=true;
      form1.Label91.Visible:=true;
      form1.button75.Visible:=true;
      form1.Edit53.Visible:=true;
//      form1.Edit54.Visible:=true;   // October11,2024 percentexchage

      if CCCP_style=0 then Form1.label91.caption:='C';
      if CCCP_style=1 then form1.label91.caption:='P';
      if CCCP_style=2 then form1.label91.caption:='C+P';

end; // chk1 checked

readln(r,s); change(s); Form1.edit53.text:=s;   CCCP:=StrToFloat(s);
// October11,2024 Percent of exchanges (Pex) for Las Vegas
// Pex =0.1 means 10% Pex=0 means Las Vegas without change of split
readln(r,s); change(s); Form1.edit54.text:=s;  // Percentexchange:=StrToFloat(s);

for k:=34 to 69 do dobutton(k);

      closefile(r);

//form1.Button10.Visible:=true;
form1.Button14.Visible:=true;
form1.Button16.Visible:=true;

if (not form1.CheckBox32.Checked) and (not form1.CheckBox21.Checked)
then form1.CheckBox32.Checked:=True; // no GRAPH no SMILES -> Let GRAPH will be

if form1.CheckBox32.Checked then // GRAPH is representation of molecules
if not
   ( form1.checkBox29.checked or // if no type of graph is not assigned
     form1.checkBox30.checked or // then HSG is activated
     form1.checkBox31.checked     ) then form1.checkBox30.checked:=TRUE;


// GRAPH must be only one ...
if form1.CheckBox29.Checked then  // ... HFG
begin
form1.CheckBox30.Checked:=False;
form1.CheckBox31.Checked:=False;
end;

if form1.CheckBox30.Checked then  // ... HSG
begin
form1.CheckBox29.Checked:=False;
form1.CheckBox31.Checked:=False;
end;

if form1.CheckBox31.Checked then  // ... GAO
begin
form1.CheckBox29.Checked:=False;
form1.CheckBox30.Checked:=False;

form1.CheckBox4.Checked:=False;
form1.CheckBox19.Checked:=False;
form1.CheckBox16.Checked:=False;
form1.CheckBox8.Checked:=False;
form1.CheckBox5.Checked:=False;

end;

if not form1.CheckBox32.Checked then // graph is not selected
begin
form1.checkBox30.Checked:=false;
form1.checkBox29.Checked:=false;
form1.checkBox31.Checked:=false;
form1.checkBox9.Checked:=false;
form1.checkBox28.Checked:=false;
form1.checkBox18.Checked:=false;
form1.checkBox10.Checked:=false;

form1.checkBox6.Checked:=false;
form1.checkBox12.Checked:=false;
form1.checkBox13.Checked:=false;
//form1.checkBox11.Checked:=false;
form1.checkBox20.Checked:=false;

form1.checkBox5.Checked:=false;      // c3
form1.checkBox8.Checked:=false;      // c4
form1.checkBox16.Checked:=false;     // c5
form1.checkBox19.Checked:=false;     // c6
form1.checkBox4.Checked:=false;      // c7

form1.checkBox36.Checked:=false;     // pt4
form1.checkBox37.Checked:=false;      // vs3

      // June 20, 2018  save

form1.checkBox38.checked :=False; // p2 nn
form1.checkBox39.checked :=False; //

form1.checkBox40.checked :=False; //
form1.checkBox41.checked :=False; //
form1.checkBox42.checked :=False; //
form1.checkBox43.checked :=False; //
//form1.checkBox44.checked :=False; //
form1.checkBox45.checked :=False; //
form1.checkBox46.checked :=False; //
form1.checkBox47.checked :=False; //
form1.checkBox48.checked :=False; //
form1.checkBox49.checked :=False; //
form1.checkBox50.checked :=False; //

form1.checkBox51.checked :=False; //
form1.checkBox52.checked :=False; //
form1.checkBox53.checked :=False; //
form1.checkBox54.checked :=False; //
form1.checkBox55.checked :=False; //
form1.checkBox56.checked :=False; //
//form1.checkBox57.checked :=False; //
form1.checkBox58.checked :=False; //
//form1.checkBox59.checked :=False; //
form1.checkBox60.checked :=False; //

form1.checkBox61.checked :=False; //
form1.checkBox62.checked :=False; //
form1.checkBox63.checked :=False; //
form1.checkBox64.checked :=False; //
form1.checkBox65.checked :=False; //
form1.checkBox66.checked :=False; //
form1.checkBox67.checked :=False; //
form1.checkBox68.checked :=False; //
form1.checkBox69.checked :=False; //
form1.checkBox70.checked :=False; //

form1.checkBox71.checked :=False; //
form1.checkBox72.checked :=False; //
form1.checkBox73.checked :=False; //
form1.checkBox74.checked :=False; //
//form1.checkBox75.checked :=False; //
form1.checkBox76.checked :=False; //
form1.checkBox77.checked :=False; //
form1.checkBox78.checked :=False; //
form1.checkBox79.checked :=False; //
form1.checkBox80.checked :=False; //

form1.checkBox81.checked :=False; //
form1.checkBox82.checked :=False; //
//form1.checkBox83.checked :=False; //
form1.checkBox84.checked :=False; //
form1.checkBox85.checked :=False; //
form1.checkBox86.checked :=False; //
form1.checkBox87.checked :=False; //
form1.checkBox88.checked :=False; //
form1.checkBox89.checked :=False; //
//form1.checkBox90.checked :=False; //

form1.checkBox91.checked :=False; //
form1.checkBox92.checked :=False; //
form1.checkBox93.checked :=False; //
form1.checkBox94.checked :=False; //
form1.checkBox95.checked :=False; //
form1.checkBox96.checked :=False; //
form1.checkBox97.checked :=False; //
//form1.checkBox98.checked :=False; //
form1.checkBox99.checked :=False; //
form1.checkBox100.checked :=False; //

form1.checkBox101.checked :=False; //
form1.checkBox102.checked :=False; //
form1.checkBox103.checked :=False; //
form1.checkBox104.checked :=False; //
form1.checkBox105.checked :=False; //
form1.checkBox106.checked :=False; //
form1.checkBox107.checked :=False; //
form1.checkBox108.checked :=False; //
form1.checkBox109.checked :=False; //
form1.checkBox110.checked :=False; //

//form1.checkBox111.checked :=False; //
form1.checkBox112.checked :=False; //
form1.checkBox113.checked :=False; //
form1.checkBox114.checked :=False; //
form1.checkBox115.checked :=False; //
form1.checkBox116.checked :=False; //
form1.checkBox117.checked :=False; //
form1.checkBox118.checked :=False; //
form1.checkBox119.checked :=False; //
form1.checkBox120.checked :=False; //

form1.checkBox121.checked :=False; //
form1.checkBox122.checked :=False; //
form1.checkBox123.checked :=False; //
form1.checkBox124.checked :=False; //
form1.checkBox125.checked :=False; //
//form1.checkBox126.checked :=False; //
form1.checkBox127.checked :=False; //
form1.checkBox128.checked :=False; //
form1.checkBox129.checked :=False; //
form1.checkBox130.checked :=False; //

form1.checkBox131.checked :=False; //
form1.checkBox132.checked :=False; //
form1.checkBox133.checked :=False; //
form1.checkBox134.checked :=False; //
form1.checkBox135.checked :=False; //
form1.checkBox136.checked :=False; //
form1.checkBox137.checked :=False; //


//// june 20, 2018 end



end; // not checkbox32 checked = graph is not selcetd

if not form1.CheckBox21.Checked then // SMILES is not selecetd
begin
form1.checkBox22.Checked:=false;
form1.checkBox23.Checked:=false;
form1.checkBox24.Checked:=false;
form1.checkBox25.Checked:=false;
form1.checkBox27.Checked:=false;
//form1.checkBox17.Checked:=false;
form1.checkBox1.Checked:=false;
form1.checkBox2.Checked:=false;
form1.checkBox3.Checked:=false;
form1.CheckBox11.checked:=false; // this is PAIR
form1.CheckBox44.Checked:=False; // Cmax

form1.checkBox59.Checked:=false; // April6,2023
form1.CheckBox98.checked:=false; // If not SMILIES then NO symmetry
form1.CheckBox35.Checked:=False; // XYX, XYYX, XYZYX


for k:=1 to 8 do
for kk:=1 to 8 do app[k,kk]:=-1;
for k:=34 to 69 do dobutton(k);

end; // not checkbox21 checked = SMILES is not selcetd

if form1.CheckBox32.Checked then // graph is selected
if (
   (form1.CheckBox9. checked=false) and
   (form1.CheckBox28.checked=false) and
   (form1.CheckBox18.checked=false) and
   (form1.CheckBox6. checked=false) and
   (form1.CheckBox12.checked=false) and
   (form1.CheckBox13.checked=false) and
   (form1.CheckBox20.checked=false) and
   (form1.CheckBox4. checked=false) and
   (form1.CheckBox19.checked=false) and
   (form1.CheckBox16.checked=false) and
   (form1.CheckBox8.checked=false)  and
   (form1.CheckBox5.checked=false)  and

            // June 20, 2018  save

( form1.checkBox38.checked =False) and // p2 nn
( form1.checkBox39.checked =False) and //

( form1.checkBox40.checked =False) and //
( form1.checkBox41.checked =False) and //
( form1.checkBox42.checked =False) and //
( form1.checkBox43.checked =False) and //
( form1.checkBox44.checked =False) and //
( form1.checkBox45.checked =False) and //
( form1.checkBox46.checked =False) and //
( form1.checkBox47.checked =False) and //
( form1.checkBox48.checked =False) and //
( form1.checkBox49.checked =False) and //
( form1.checkBox50.checked =False) and //

( form1.checkBox51.checked =False) and //
( form1.checkBox52.checked =False) and //
( form1.checkBox53.checked =False) and //
( form1.checkBox54.checked =False) and //
( form1.checkBox55.checked =False) and //
( form1.checkBox56.checked =False) and //
( form1.checkBox57.checked =False) and //
( form1.checkBox58.checked =False) and //
( form1.checkBox59.checked =False) and //
( form1.checkBox60.checked =False) and //

( form1.checkBox61.checked =False) and //
( form1.checkBox62.checked =False) and //
( form1.checkBox63.checked =False) and //
( form1.checkBox64.checked =False) and //
( form1.checkBox65.checked =False) and //
( form1.checkBox66.checked =False) and //
( form1.checkBox67.checked =False) and //
( form1.checkBox68.checked =False) and //
( form1.checkBox69.checked =False) and //
( form1.checkBox70.checked =False) and //

( form1.checkBox71.checked =False) and //
( form1.checkBox72.checked =False) and //
( form1.checkBox73.checked =False) and //
( form1.checkBox74.checked =False) and //
( form1.checkBox75.checked =False) and //
( form1.checkBox76.checked =False) and //
( form1.checkBox77.checked =False) and //
( form1.checkBox78.checked =False) and //
( form1.checkBox79.checked =False) and //
( form1.checkBox80.checked =False) and //

( form1.checkBox81.checked =False) and //
( form1.checkBox82.checked =False) and //
( form1.checkBox83.checked =False) and //
( form1.checkBox84.checked =False) and //
( form1.checkBox85.checked =False) and //
( form1.checkBox86.checked =False) and //
( form1.checkBox87.checked =False) and //
( form1.checkBox88.checked =False) and //
( form1.checkBox89.checked =False) and //
( form1.checkBox90.checked =False) and //

( form1.checkBox91.checked =False) and //
( form1.checkBox92.checked =False) and //
( form1.checkBox93.checked =False) and //
( form1.checkBox94.checked =False) and //
( form1.checkBox95.checked =False) and //
( form1.checkBox96.checked =False) and //
( form1.checkBox97.checked =False) and //
( form1.checkBox98.checked =False) and //
( form1.checkBox99.checked =False) and //
( form1.checkBox100.checked =False) and //

( form1.checkBox101.checked =False) and //
( form1.checkBox102.checked =False) and //
( form1.checkBox103.checked =False) and //
( form1.checkBox104.checked =False) and //
( form1.checkBox105.checked =False) and //
( form1.checkBox106.checked =False) and //
( form1.checkBox107.checked =False) and //
( form1.checkBox108.checked =False) and //
( form1.checkBox109.checked =False) and //
( form1.checkBox110.checked =False) and //

( form1.checkBox111.checked =False) and //
( form1.checkBox112.checked =False) and //
( form1.checkBox113.checked =False) and //
( form1.checkBox114.checked =False) and //
( form1.checkBox115.checked =False) and //
( form1.checkBox116.checked =False) and //
( form1.checkBox117.checked =False) and //
( form1.checkBox118.checked =False) and //
( form1.checkBox119.checked =False) and //
( form1.checkBox120.checked =False) and //

( form1.checkBox121.checked =False) and //
( form1.checkBox122.checked =False) and //
( form1.checkBox123.checked =False) and //
( form1.checkBox124.checked =False) and //
( form1.checkBox125.checked =False) and //
( form1.checkBox126.checked =False) and //
( form1.checkBox127.checked =False) and //
( form1.checkBox128.checked =False) and //
( form1.checkBox129.checked =False) and //
( form1.checkBox130.checked =False) and //

( form1.checkBox131.checked =False) and //
( form1.checkBox132.checked =False) and //
( form1.checkBox133.checked =False) and //
( form1.checkBox134.checked =False) and //
( form1.checkBox135.checked =False) and //
( form1.checkBox136.checked =False) and //
( form1.checkBox137.checked =False) and //

   (form1.CheckBox10.checked=false)
   ) then form1.checkbox9.checked:=True;

if form1.CheckBox21.Checked then // SMILES is selected
if (
   (form1.CheckBox22.checked=false) and
   (form1.CheckBox23.checked=false) and
   (form1.CheckBox25.checked=false) and
   (form1.CheckBox27.checked=false) and
//   (form1.CheckBox17.checked=false) and
   (form1.CheckBox1.checked=false)  and
   (form1.CheckBox2.checked=false)  and
   (form1.CheckBox44.checked=false)  and
   (form1.CheckBox3.checked=false)
   ) then form1.checkbox1.checked:=True;

if not form1.CheckBox26.Checked then  // if ideal K,k' is not selected
begin                                 // then remove from display
form1.Edit31.Visible:=false;          // dK digits
form1.Label16.Visible:=false;         // weight
form1.Label47.Visible:=false;         // dK
end;

IIC_style:=strToInt(form1.edit28.text);
if not (IIC_style in [0,1,2]) then begin IIC_style:=0; form1.Edit28.Text:='0'; end;
if IIC_style=0 then form1.label54.caption:='C';
if IIC_style=1 then form1.label54.caption:='P';
if IIC_style=2 then form1.label54.caption:='C+P';

CCI_style:=strToInt(form1.edit29.text);
if not (CCI_style in [0,1,2]) then begin CCI_style:=0; form1.Edit29.Text:='0'; end;
if CCI_style=0 then form1.label80.caption:='C';
if CCI_style=1 then form1.label80.caption:='P';
if CCI_style=2 then form1.label80.caption:='C+P';

end;  // load method


procedure TForm1.Button13Click(Sender: TObject);
var fl:string;
    f:textfile;
    k,j:integer;
    c:char;
begin
series:='n';
//beep;

APCV := not APCV;
if apcv then button13.Caption:='APCV style'
        else button13.Caption:='APC style';
end;

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
var c:char;   r:integer;
begin

//beep;

r:=messageDLG('Termination of the progtram?',mtConfirmation,[mbYes,mbCancel],0);
if r=mrYes then halt;
//if r=mrNO then goto outof;
//if r=mrCancel then goto outof;

c:=key;
if c='q' then stopping:=True;

end;

function increase(CW:real):boolean;
var
rez:boolean;
begin
rez:=false;
if (scheme='+') then rez:=CW>0.0;
if (scheme='*') then rez:=CW>1.0;
increase:=rez;
end; // increas CW>0 (additive scheme) >1 (multiplicative scheme)

function increasers(SAnmr,Nprobes:integer):boolean;
var k:integer;
    rez:boolean;
begin
rez:=true;
for k:=1 to nprobes do rez:=rez and increase( CW[k,SAnmr] );
increasers:=rez;
end; // increasers

function decrease(CW:real):boolean;
var
rez:boolean;
begin
rez:=false;
if scheme='+' then rez:=CW<0.0;
if scheme='*' then rez:=CW<1.0;
decrease:=rez;
end; // increas CW>0 (additive scheme) >1 (multiplicative scheme)

function decreasers(SAnmr,Nprobes:integer):boolean;
var k:integer;
    rez:boolean;
begin
rez:=true;
for k:=1 to nprobes do rez:=rez and decrease( CW[k,SAnmr] );
decreasers:=rez;
end; // decreasers

function max_trns:integer;
var k,max:integer;
begin
max:=trns[1];
for k:=1 to n_glb do
if max<trns[k] then max:=trns[k];
max_trns:=max;
end; // max_trns

Procedure SaveProbeStatOrder(var limni:integer;var Tt:integer);
//Const Depth=15;
var                                // T is threshold = limni...
    k,j,i,f2,
    maxtrns, max,
    DepthInterpret,
    nmr,
    nnn,
    nprobes,
    category,
    t:integer;
                   // June 14, 2016 Depth of mechanistic interpretation
    d,             // s-file where only limDepth string increase and decrease
    z:textfile;    // s-file
    name:string;

begin // #s (statistics) and p# (promoters of increase or decrease of endpoint

maxtrns:=max_trns;

depthInterpret:=StrToInt(form1.Edit26.Text);

nprobes:=StrToInt(form1.Edit24.Text);

name:=dir+'/s'+IntToStr(limni)+'.txt';
assign(z,name);
rewrite(z);

name:=dir+'/p'+IntToStr(limni)+'.txt'; // p = promoters increase/decrease only
assign(d,name);
rewrite(d);

t:=tt;

Writeln(z,'This file contains the statistical classification of structural attributes (SA)');
writeln(z);
writeln(z,DotInSMILES);
writeln(z);
// if form1.CheckBox32.Checked then
// hybrid place
begin
if form1.CheckBox30.Checked then
writeln(z,'Hydrogen suppressed graph (HSG) is used in the model');
if form1.CheckBox29.Checked then
writeln(z,'Hydrogen filled graph (HFG) is used in the model');
if form1.CheckBox31.Checked then
writeln(z,'Graph of Atomic Orbitals (GAO) is used in the model');
end;

if form1.CheckBox21.Checked then
writeln(z,'SMILES is used in the model');

writeln(z,'The classification is follows:');
writeln(z,'- if SA has CW(SA)>0 in all probes of the Monte Carlo optimization');
writeln(z,'then the SA is a promoter of the Endpoint increase (List 1)');
writeln(z,'- if SA has CW(SA)<0 in all probes of the Monte Carlo optimization');
writeln(z,'then the SA is a promoter of the Endpoint decrease (List 2)');
writeln(z,'- if SA has CW(SA)>0 together with CW(SA)<0 ');
writeln(z,'then the role of SA is undefined (list 3)');
writeln(z,'- if SA is blocked, i.e., CW(SA)=0 ');
writeln(z,'then the SA without of the model (list 4)');
writeln(z);
writeln(z,'Each list is starting by No.=1, the ID is the numbering in total list of attributes.');
writeln(z);
writeln(z,'N1, N2, and N3 are numbers of SMILES which contain SA ');
writeln(z,'in training, invisible training, and calibration sets, respectively');
writeln(z);

write(z,
'  No. :  ID :',
' SAk        :');

for j:=1 to nprobes do write(z,' CWs Probe '+IntToStr(j)+':');

write  (z,
'        N1  :',
'        N2  :',
'        N3  :',
' Defect[SAk]:'
);


writeln(z);

writeln(d,'This file conatins promoters of increase/decrease for endpoint');
writeln(d,'according to selected "depth of interpretation"');
writeln(d,'The N1, N2, and N3 are the number of SMILES which contain');
writeln(d,'given attribute (SAk) in training, invisible training, and in ');
writeln(d,'calibration sets, respectively');
writeln(d,'Defect[SAk] is the difference of probabilities of SAk in training');
writeln(d,'and calibration sets, divided by sum of total numbers of the ');
writeln(d,'SAk in the training and calibration sets');
writeln(d,'If attribute SAk absent in training set then defect=1 (maximum)');
writeln(d);



write(d,
'  No. :  ID :',
' SAk        :');

for j:=1 to nprobes do write(d,' CWs Probe '+IntToStr(j)+':');

write  (d,
'        NSs :',
'        NSc :',
'        NSv :',
' Defect[SAk]:'
);


writeln(d);

////////////////////////////////////////////////////////////////////////   1

max:=maxtrns+1;
nmr:=0;

repeat  max:=max-1;

for i:=1 to n_glb do
begin

if increasers(i,nprobes) then
if trns[i]=max then
begin
inc(nmr);

write(z,nmr:6,':',i:5,':');

for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]);
write(z,':');

f2:=ffd; if cw[1,i]=off then f2:=1; // formats 0.9978178 == 1.0

for j:=1 to nprobes do write(z,CW[j,i]:12:f2,':');

write(z,trns[i]:12,':');
write(z,clbs[i]:12,':');
write(z,tsts[i]:12,':');
write(z,CWdefect[i]:12:4);

writeln(z);

if nmr<=DepthInterpret then
begin
write(d,nmr:6,':',i:5,':');

for j:=1 to MaxCharSF do write(d,global_SF_list[i][j]);
write(d,':');

f2:=ffd; if cw[1,i]=off then f2:=1; // formats 0.9978178 == 1.0

for j:=1 to nprobes do write(d,CW[j,i]:12:f2,':');

write(d,trns[i]:12,':');
write(d,clbs[i]:12,':');
write(d,tsts[i]:12,':');
write(d,CWdefect[i]:12:4);

writeln(d);
end; // nmr<Depth


end; // detected category X (1 increase,2 decrease,3 undefined, and 4 blocked)
end; // next i

until max=0;

/////////////////////////////////////////////////////////////////////// end 1
////////////////////////////////////////////////////////////////////////   2


max:=maxtrns+1;
nmr:=0;

repeat  max:=max-1;

for i:=1 to n_glb do
begin
if decreasers(i,nprobes) then
if trns[i]=max then
begin
inc(nmr);

write(z,nmr:6,':',i:5,':');

for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]);
write(z,':');

f2:=7; if cw[1,i]=off then f2:=1; // formats 0.9978178 == 1.0

for j:=1 to nprobes do write(z,CW[j,i]:12:ffd,':');

write(z,trns[i]:12,':');
write(z,clbs[i]:12,':');
write(z,tsts[i]:12,':');
write(z,CWdefect[i]:12:4);
writeln(z);

if nmr<=DepthInterpret then
begin
write(d,nmr:6,':',i:5,':');

for j:=1 to MaxCharSF do write(d,global_SF_list[i][j]);
write(d,':');

f2:=7; if cw[1,i]=off then f2:=1; // formats 0.9978178 == 1.0

for j:=1 to nprobes do write(d,CW[j,i]:12:ffd,':');

write(d,trns[i]:12,':');
write(d,clbs[i]:12,':');
write(d,tsts[i]:12,':');
write(d,CWdefect[i]:12:4);
writeln(d);

end; // nmr < depth
end; // detected category X (1,2,and 3)
end; // next i

until max=0;

/////////////////////////////////////////////////////////////////////// end 2
////////////////////////////////////////////////////////////////////////   3

max:=maxtrns+1;
nmr:=0;

repeat  max:=max-1;

for i:=1 to n_glb do
begin

if
not increasers(i,nprobes) and
not decreasers(i,nprobes) and (trns[i]>=LimNI) then
if trns[i]=max then
begin
inc(nmr);
write(z,nmr:6,':',i:5,':');

for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]);
write(z,':');

f2:=ffd; if cw[1,i]=off then f2:=1; // formats 0.9978178 == 1.0

for j:=1 to nprobes do write(z,CW[j,i]:12:f2,':');

write(z,trns[i]:12,':');
write(z,clbs[i]:12,':');
write(z,tsts[i]:12,':');
write(z,CWdefect[i]:12:4);

writeln(z);
end; // detected category X (1,2,and 3)
end; // next i
until max=0;

/////////////////////////////////////////////////////////////////////// end 3
////////////////////////////////////////////////////////////////////////   4

max:=maxtrns+1;
nmr:=0;

repeat  max:=max-1;

for i:=1 to n_glb do
begin

if trns[i]<LimNI then
if trns[i]=max   then
begin
inc(nmr);
write(z,nmr:6,':',i:5,':');

for j:=1 to MaxCharSF do write(z,global_SF_list[i][j]);
write(z,':');

f2:=7; if cw[1,i]=off then f2:=1; // formats 0.9978178 == 1.0

for j:=1 to nprobes do write(z,CW[j,i]:12:f2,':');

write(z,trns[i]:12,':');
write(z,clbs[i]:12,':');
write(z,tsts[i]:12,':');
write(z,CWdefect[i]:12:4);
writeln(z);
end; // detected category X (1,2,and 3)
end; // next i
until max=0;

/////////////////////////////////////////////////////////////////////// end 4

writeln(z);

closefile(z); // all statistics
closefile(d); // depth of mechanistic interpretation

end; // Save Probe Stat Order

procedure DefineRecFile(var delme:string);
var
    fl:TSearchRec;
    fn,
    f1:integer;
    s:string;
begin

delme:='No';

f1:=findfirst('*.txt',0,fl);      // whether txt takes place? F1=0
//showmessage(inttostr(f1));
if f1<>0 then
begin
showmessage('No file.txt is available. Please insert desired txt file.');
end; // there are no txt files

s:=fl.Name;
//form1.combobox1.items.add(s);

//showmessage(s); // shoe the first file txt

repeat
 fn:=findNext(fl);
 if fn=0 then
 begin
  s:=fl.Name;                       // name of txt file
//  form1.ComboBox1.Items.Add(s);     // insert string into combobox1
                                    //  showmessage(s); show file txt
  if  (s[1]='#')
  and (s[2]='R')
  and (s[3]='e')
  and (s[4]='c')
  then
  begin
  delme:=s;
  exit;
  end; // detectetd #Rec...

 end;
until fn<>0;

//repeat
//showmessage('Define work file');
//until workfile='';

//showmessage('Extraction of files.txt is completed');

end; // Define Recommended file

procedure savemethod;
label outoff;
var r:text;
    x:integer;
    k,kk:integer;
begin

if form1.Edit1.Text='***' then
begin
//showmessage('Method is not defined');
goto outoff;
end;

if form1.RadioButton2.Checked then
begin
//form1.checkBox24.checked:=False;
end; // Classic scheme is selected...

      assign(r,form1.Edit19.Text); rewrite(r);

      writeln(r,form1.edit1.text); // smiles file
      writeln(r,form1.edit9.text); // nit
      writeln(r,form1.edit3.text); // ID for Demo DCW
      writeln(r,form1.edit20.text); // sd
      writeln(r,form1.edit21.text); // ssd
      writeln(r,form1.edit10.text); // IICweight
      writeln(r,form1.edit22.text); // limN start
      writeln(r,form1.edit23.text); // limN finish
      writeln(r,form1.edit24.text); // N probes
      writeln(r,form1.edit19.text); // file name for method


If form1.checkBox1.checked then writeln(r,'y') else writeln(r,'n'); //     -s
If form1.checkBox2.checked then writeln(r,'y') else writeln(r,'n'); //     -ss
If form1.checkBox3.checked then writeln(r,'y') else writeln(r,'n'); //     -sss
If form1.checkBox4.checked then writeln(r,'y') else writeln(r,'n'); //     + (
If form1.checkBox5.checked then writeln(r,'y') else writeln(r,'n'); //     + =
If form1.checkBox6.checked then writeln(r,'y') else writeln(r,'n'); //     + pt2
If form1.checkBox7.checked then writeln(r,'y') else writeln(r,'n'); //     + Index of correlation confidence
If form1.checkBox8.checked then writeln(r,'y') else writeln(r,'n'); //     + Oxygen
If form1.checkBox9.checked then writeln(r,'y') else writeln(r,'n'); //     + ec0
If form1.checkBox10.checked then writeln(r,'y') else writeln(r,'n'); //    + ec3
If form1.checkBox11.checked then writeln(r,'y') else writeln(r,'n'); //    + PAIR
If form1.checkBox12.checked then writeln(r,'y') else writeln(r,'n'); //    + pt3
If form1.checkBox13.checked then writeln(r,'y') else writeln(r,'n'); //    + vs2
If form1.checkBox14.checked then writeln(r,'y') else writeln(r,'n'); //    + 1
If form1.checkBox15.checked then writeln(r,'y') else writeln(r,'n'); //    + 2
If form1.checkBox16.checked then writeln(r,'y') else writeln(r,'n'); //    + 3
If form1.checkBox17.checked then writeln(r,'y') else writeln(r,'n'); //    + Classification
If form1.checkBox18.checked then writeln(r,'y') else writeln(r,'n'); //    + ec2
If form1.checkBox19.checked then writeln(r,'y') else writeln(r,'n'); // + Csp3
If form1.checkBox20.checked then writeln(r,'y') else writeln(r,'n'); // + csp2
If form1.checkBox21.checked then writeln(r,'y') else writeln(r,'n'); // SMILES represent
If form1.checkBox22.checked then writeln(r,'y') else writeln(r,'n'); // \/cistrans
If form1.checkBox23.checked then writeln(r,'y') else writeln(r,'n'); // @@,@ chir

If form1.CheckBox24.Checked then writeln(r,'y') else writeln(r,'n'); // AAchaos May17,2023
If form1.checkBox25.checked then writeln(r,'y') else writeln(r,'n'); // BOND
If form1.checkBox26.checked then writeln(r,'y') else writeln(r,'n'); // Balance k and k'
If form1.checkBox27.checked then writeln(r,'y') else writeln(r,'n'); // #HALONOSP21
If form1.checkBox28.checked then writeln(r,'y') else writeln(r,'n'); // ec1
If form1.checkBox29.checked then writeln(r,'y') else writeln(r,'n'); // P'
If form1.checkBox30.checked then writeln(r,'y') else writeln(r,'n'); // F'
If form1.checkBox31.checked then writeln(r,'y') else writeln(r,'n'); // GAO
// June 8, 2018
If form1.checkBox36.checked then writeln(r,'y') else writeln(r,'n'); // pt4
If form1.checkBox37.checked then writeln(r,'y') else writeln(r,'n'); // vs3


If form1.checkBox32.checked then writeln(r,'y') else writeln(r,'n'); // GRAPH


if authomat then writeln(r,'y');    // interactive or authomatic mode
if save_all_CWs then writeln(r,'y');  // save all or only active SFk

if form1.RadioButton2.Checked then writeln(r,'y') else writeln(r,'n');
                                                         // Yes=(TC):t
                                                         // No =(T)(C):t

writeln(r,scheme);


If PAmodify                 then writeln(r,'y') else writeln(r,'n'); // PAmodify

      writeln(r,form1.edit25.text); // LimS or LimN

      writeln(r,form1.edit26.text);  // dept of interpretation
      writeln(r,form1.edit27.text);
      writeln(r,form1.edit28.text);  // S:f1:f2
      writeln(r,form1.edit29.text);


      if
     not (form1.CheckBox33.Checked) and
     not (form1.CheckBox34.Checked) and
     not (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(0);
      if
         (form1.CheckBox33.Checked) and
     not (form1.CheckBox34.Checked) and
     not (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(1);

      if
     not (form1.CheckBox33.Checked) and
         (form1.CheckBox34.Checked) and
     not (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(10);

      if
     not (form1.CheckBox33.Checked) and
     not (form1.CheckBox34.Checked) and
         (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(100);

      if
         (form1.CheckBox33.Checked) and
         (form1.CheckBox34.Checked) and
     not (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(11);

      if
         (form1.CheckBox33.Checked) and
     not (form1.CheckBox34.Checked) and
         (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(101);

      if
     not (form1.CheckBox33.Checked) and
         (form1.CheckBox34.Checked) and
         (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(110);

      if
         (form1.CheckBox33.Checked) and
         (form1.CheckBox34.Checked) and
         (form1.CheckBox35.Checked) then form1.Edit30.Text:=IntToStr(111);


      writeln(r,form1.edit30.text);  // DCW:f1:f2
      writeln(r,form1.edit10.text);  // IICweight

      writeln(r,form1.edit38.text); // level of idealization
      writeln(r,form1.edit39.text); // bestLim
      writeln(r,form1.edit42.text); // dcWeight
      writeln(r,form1.edit43.text); // dRWeight

      // June 20, 2018  save

If form1.checkBox38.checked then writeln(r,'y') else writeln(r,'n'); // p2 nn
If form1.checkBox39.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox40.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox41.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox42.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox43.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox44.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox45.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox46.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox47.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox48.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox49.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox50.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox51.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox52.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox53.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox54.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox55.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox56.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox57.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox58.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox59.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox60.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox61.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox62.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox63.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox64.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox65.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox66.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox67.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox68.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox69.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox70.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox71.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox72.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox73.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox74.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox75.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox76.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox77.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox78.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox79.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox80.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox81.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox82.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox83.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox84.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox85.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox86.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox87.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox88.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox89.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox90.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox91.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox92.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox93.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox94.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox95.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox96.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox97.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox98.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox99.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox100.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox101.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox102.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox103.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox104.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox105.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox106.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox107.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox108.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox109.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox110.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox111.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox112.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox113.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox114.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox115.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox116.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox117.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox118.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox119.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox120.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox121.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox122.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox123.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox124.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox125.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox126.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox127.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox128.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox129.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox130.checked then writeln(r,'y') else writeln(r,'n'); //

If form1.checkBox131.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox132.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox133.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox134.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox135.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox136.checked then writeln(r,'y') else writeln(r,'n'); //
If form1.checkBox137.checked then writeln(r,'y') else writeln(r,'n'); //

//// January 9, 2020

for k:=1 to 8 do
for kk:=1 to 8 do writeln(r,app[k,kk]-1);

If form1.chk1.checked then writeln(r,'y') else writeln(r,'n'); // indeks correlation unity January4,2024
writeln(r,form1.edit53.text); // June11,2024
writeln(r,form1.edit54.text); // Oct11,2024 Percentage of exchange for APCV / APC

//writeln(r,strTofloat( form1.edit53.text) ); // February8,2024
      closefile(r);

      loadmethod;

outoff:
end;  // saveMethod

procedure deleteLV(dir:string);
var
    fl:TSearchRec;
    txt,
    check,
    s,
    ss,
    dirr:string;
    k,
    ff, fn,
    d:integer;
begin
dirr:=dir+'*.*';
ff:=FindFirst(dirr,0,fl);
s:=fl.Name;

//showmessage('FindFirst: '+dirr+' '+s);

if not model_is_loaded then
begin
if ff=0 then
begin

begin
ss:=dir+s;
if deleteFile(ss) then ; // showmessage(ss);

repeat
 fn:=findNext(fl);
 if fn=0 then
 begin
  s:=fl.Name;
  ss:=dir+s;
  if DeleteFile(ss) then ; // showmessage(ss+' is deleted');
 end;
until fn<>0;

//showmessage('LV - Files related to previous calculations are deleted');

end; // deleting previous files

end; // ff=0
end; // not model is loaded
end; // deleteLV(dir);



procedure deletefiles(dir:string);
var
    fl:TSearchRec;
    txt,
    check,
    s,
    ss,
    dirr:string;
    k,
    ff, fn,
    d:integer;
begin
dirr:=dir+'*.*';
ff:=FindFirst(dirr,0,fl);
s:=fl.Name;

//showmessage('FindFirst: '+dirr+' '+s);

if not model_is_loaded then
begin
if ff=0 then
begin

txt:='There are files in "'+dir+'*.*" which remain after previous calculations'+#13+
'you can delete these files in order to avoid mixture of new files'+#13+
'and files which remain after previous calculations.' +#13+
'Delete these files?';

//d:=messageDLG(txt,mtConfirmation,[mbYes,mbNo,mbCancel],0);

form1.Caption:='CORAL: Wait please...';

//if (d=mrNO) then
//showmessage('OK, Files related to previous calculation will be saved');
//if  d=mrCancel then // exit;

//if (d=mrCancel) then HALT;

//if (d=mrYES) then
begin
// showmessage('Yes is selected');
ss:=dir+s;
if deleteFile(ss) then ; // showmessage(ss);

repeat
 fn:=findNext(fl);
 if fn=0 then
 begin
  s:=fl.Name;

  ss:=dir+s;
  check:='';
  for k:=length(ss)-3 to length(ss) do check:=check+ss[k];

  if (check[1]='.') and (check[2]='t') and (check[3]='x') and (Check[4]='t') then
  if not (ss[1]='!') then
  if DeleteFile(ss) then ; // showmessage(ss+' is deleted');
 end;
until fn<>0;

//showmessage('Files related to previous calculations are deleted');

end; // deleting previous files

end; // ff=0
end; // not model is loaded
end; // deletefiles(dir);

procedure ActionOfButton28;
var f,
    CWfile:textfile;
    k,j:integer;
    CWp, // Name file contains true CWs values Dec12,2024
    fl:string;
begin

// Dec12,2024
Cwp:=dir+'Wv' + intToStr(limni-1)+'-'+ inttostr(probe-1)+'.txt';
Assign(CWfile,CWp);rewrite(CWfile);
writeln(CWfile,' Attribute  :   Weight value');

if (form1.Edit22.text=form1.Edit23.Text) and (form1.Edit22.text<>'***') then

begin

fl:= 'model/'+form1.Edit50.text;   // +'.txt'
assignfile(f,fl);
{$I-}
rewrite(f);
{$I+}
if IOResult <> 0 then
begin
showmessage('Error with File '+form1.Edit50.text+#13+
'The program will be halted');
halt;
end;  // IOresult <>0

// Jan5 2018: save current model

writeln(f,form1.edit1.text);       // name for SMILES-file
writeln(f,form1.edit9.text);       // N*
writeln(f,form1.edit39.text);      // T*
// GRAPH Boxes
if form1.checkbox32.Checked then writeln(f,'Y') else writeln(f,'N');   //   graph
if form1.checkbox30.Checked then writeln(f,'Y') else writeln(f,'N');   //   hsg
if form1.checkbox29.Checked then writeln(f,'Y') else writeln(f,'N');   //   hfg
if form1.checkbox31.Checked then writeln(f,'Y') else writeln(f,'N');   //   gao
if form1.checkbox9.Checked then writeln(f,'Y') else writeln(f,'N');   //    ec0
if form1.checkbox28.Checked then writeln(f,'Y') else writeln(f,'N');   //   ec1
if form1.checkbox18.Checked then writeln(f,'Y') else writeln(f,'N');   //   ec2
if form1.checkbox10.Checked then writeln(f,'Y') else writeln(f,'N');   //   ec3
if form1.checkbox6.Checked then writeln(f,'Y') else writeln(f,'N');   //   pt2
if form1.checkbox12.Checked then writeln(f,'Y') else writeln(f,'N');   //  pt3
if form1.checkbox13.Checked then writeln(f,'Y') else writeln(f,'N');   //  vs2
if form1.checkbox20.Checked then writeln(f,'Y') else writeln(f,'N');   //  nnc
if form1.checkbox5.Checked then writeln(f,'Y') else writeln(f,'N');   //   c3
if form1.checkbox8.Checked then writeln(f,'Y') else writeln(f,'N');   //   c4
if form1.checkbox16.Checked then writeln(f,'Y') else writeln(f,'N');   //  c5
if form1.checkbox19.Checked then writeln(f,'Y') else writeln(f,'N');   //  c6
if form1.checkbox4.Checked then writeln(f,'Y') else writeln(f,'N');   //   c7

// SMILES Boxes
if form1.checkbox21.Checked then writeln(f,'Y') else writeln(f,'N');   // smiles
if form1.checkbox22.Checked then writeln(f,'Y') else writeln(f,'N');   // nosp
if form1.checkbox23.Checked then writeln(f,'Y') else writeln(f,'N');   // halo
if form1.checkbox25.Checked then writeln(f,'Y') else writeln(f,'N');   // bond
if form1.checkbox27.Checked then writeln(f,'Y') else writeln(f,'N');   // hard
if form1.checkbox11.Checked then writeln(f,'Y') else writeln(f,'N');   // pair
if form1.checkbox1.Checked then writeln(f,'Y') else writeln(f,'N');   // s
if form1.checkbox2.Checked then writeln(f,'Y') else writeln(f,'N');   // ss
if form1.checkbox3.Checked then writeln(f,'Y') else writeln(f,'N');   // sss

if form1.RadioButton1.Checked then writeln(f,'Y') else writeln(f,'N');  // Balance
if form1.RadioButton2.Checked then writeln(f,'Y') else writeln(f,'N');  // Classic

if form1.checkbox24.Checked then writeln(f,'Y') else writeln(f,'N');   // Ideal slopes

writeln(f,form1.edit20.text);
writeln(f,form1.edit21.text);
writeln(f,form1.edit22.text);
writeln(f,form1.edit23.text);
writeln(f,form1.edit24.text);

writeln(f,form1.edit42.text);  // dC
writeln(f,form1.edit43.text);  // dR

writeln(f,form1.edit45.text);  // C0
writeln(f,form1.edit46.text);  // C1

writeln(f,StrToFloat(form1.edit4.text) );
writeln(f,StrToFloat(form1.edit5.text) );

writeln(f,n_glb);
for k:=1 to n_glb do
begin
  if CWdefect[k]>0.99 then CW[1,k]:=0.0; // February19,2025
for j:=1 to MaxCharSF do write(f,global_SF_list[k][j]);
writeln(f,cw[1,k],CWdefect[k]);

// Dec12,2024
for j:=1 to MaxCharSF do
write(CWfile,global_SF_list[k][j]);
writeln(CWfile,':',cw[1,k]:12:4);

end;
Close(CWfile); // print true values of CWs Dec12,2024


writeln(f,form1.edit39.text); // threshold

writeln(f,nsms);
for k:=1 to nsms do
begin
write(f,nuc[k,0]:7);
for j:=1 to nuc[k,0] do write(f,nuc[k,j]:7);
writeln(f);
end; // k

doDefectSMILES;

AveDefectSMILES:=0.0;
for k:=1 to nsms do
begin
AveDefectSMILES:=AveDefectSMILES + DefectSMILES[k];
end; // k

AveDefectSMILES:=AveDefectSMILES / nsms;

writeln(f,AveDefectSMILES);

//oct25 2017

for k:=1 to n_glb do
writeln(f,TRNs[k]:7,CLBs[k]:7,TSTs[k]:7,TRN[k]:7,CLB[k]:7,TST[k]:7);
writeln(f,SMILESAk);
writeln(f,form1.edit39.text);

writeln(f,form1.edit36.text); // W%
writeln(f,form1.edit13.text); // III
writeln(f,form1.edit12.text); // II0
writeln(f,form1.edit8.text);  // IOI
writeln(f,form1.edit32.text); // IOO
writeln(f,form1.edit33.text); // ALL
writeln(f,form1.edit35.text); // SplitDefect
writeln(f,form1.edit2.text);  // NormSplitDefect
(*
showmessage(
form1.Edit36.Text+#13+
form1.Edit13.Text+#13+
form1.Edit12.Text+#13+
form1.Edit8.Text+#13+
form1.Edit32.Text+#13+
form1.Edit33.Text+#13+
form1.Edit35.Text
);
*)
closefile(f);
savemethod;
//halt;

end   // edit22=edit23, Tstart=Tmaximum
else showmessage('System is not ready for saving');

end; // ActionOfButton28

procedure TForm1.Button28Click(Sender: TObject);
var k:integer;
begin

SAS:=TRUE;

ActionOfButton28;

halt;

end; // button 28


procedure auto;
Label
    Restart, onlys1;
var
    CharmName,          // Characteristics of models TRN_Alpha_plus, etc.
    x2,x6,x7,
    mss,     // message
    sms,     // sms for external DCW calculation ???
    op,      // optimization data
    wp,      // work???
    dc,      // descriptor calculation
    md,      // model
    ec,      // file of evolution of correlations
    id       // idealization = del worst outlier, del worst outlier ... 5 times
    :string;
    limn0, limne, nprobes, rr:integer;
                        // R-TRN, R'-CLB, R''-TST
    CharM,              // Charm = Threshold-R-R'-R''-TRN_Alpha_plus-...
    a,r,rrr:text;
                        // TRN training, CLB calibration, TST test
    A12,A13,A23,        // prevalence SAk in TRN-CLB A12
                        //                   TRN-TST A13
                        //                   CLB-TST A23
    c0,c1, dc0,dc1,

    rt05,rc05,re05,

    rt,st,ft,
    rc,sc,fc,
    re,se,fe:            real;

    nt,nc,ne:            integer;

    Rm2av,
    art,ast,aft,
    arc,asc,afc,
    are,ase,afe:         real;
               // Formats:
    fr1,fr2,   // R
    fs1,fs2,   // S
//    fd1,fd2,   // DCW
    k:integer;
    nnoprint:boolean;
    s:string;
    fl:TSearchRec;
    ss,
    dirr:string;
    ff, fn,
    d:integer;
    txt:string;
    sa:integer;

    TRN_CLB_max_plus,

    TRN_max_alpha_minus,
    TRN_max_alpha_plus ,
    CLB_max_alpha_minus,
    CLB_max_alpha_plus ,
    TST_max_alpha_minus,
    TST_max_alpha_plus :real;

    t:integer;

    sum1,sum2:real;

    BestN_R2,      //
    BestN_RMSE,
    minRMSE,       // minimal RMSE for test set
    maxRtst:real;  // maximal correlation coefficient for test set
    BestT_RMSE,
    BestT_R2:integer; // T* for the search
    delme:string; // for delete old recommend T and N .txt

    defect:real; // split defect = P - P' / N - N'
    Nact:real;   // number of active attributes
    NormSpltDef:real; // normalized defect = [ (defect * T) / Nact ]* T^(1/3)
    nccc:integer; // to calculate CCC

begin

//if model_is_loaded then showmessage('Model is loaded')
//                   else showmessage('Model is not loaded');

form1.Button28.visible:=false;
form1.Button29.visible:=false;
form1.Edit50.visible:=false;

nnoprint:=false;

(*
FR1:=StrToInt(form1.edit26.text); // format R
FR2:=StrToInt(form1.edit27.text);
Fs1:=StrToInt(form1.edit28.text); // format s
Fs2:=StrToInt(form1.edit29.text);
*)
// jan 29, 2018
FR1:=12; FR2:=4;
FS1:=10; FS2:=3;
//ffd:=StrToInt(form1.edit30.text); // format DCW:12:fd
//Fp :=StrToInt(form1.edit31.text); // format PA:12:fp

dCweight:=StrToFloat(Form1.Edit38.Text);    // weight for Correlation Intensity Index CII
dRweight:=StrToFloat(Form1.Edit43.Text);    // dRweight
dKweight:=StrToFloat(Form1.Edit10.Text);    // weight for Index of Ideality of correlation IIC

series:='y';

limn0  :=StrToInt(form1.Edit22.Text);
limnE  :=StrToInt(form1.Edit23.Text);
nprobes:=StrToInt(form1.Edit24.Text);

if limn0=limne then
begin dir:='model/';
probe:=1
end
else
begin
dir:='search/';
form1.Button10.Visible:=false;
form1.Label19.Visible:=true;
end; // model/  else

dirr:=dir+'*.*';
ff:=FindFirst(dirr,0,fl);
s:=fl.Name;

//showmessage('FindFirst: '+dirr+' '+s);

if not model_is_loaded then
begin
if ff=0 then
begin

txt:='There are files in "'+dir+'*.*" which remain after previous calculations'+#13+
'you can delete these files in order to avoid mixture of new files'+#13+
'and files which remain after previous calculations.' +#13+
'Delete these files?';

//d:=messageDLG(txt,mtConfirmation,[mbYes,mbNo,mbCancel],0);

form1.Caption:='CORAL: Wait please...';

//if (d=mrNO) then
//showmessage('OK, Files related to previous calculation will be saved');
//if  d=mrCancel then // exit;

//if (d=mrCancel) then HALT;

//if (d=mrYES) then
begin
// showmessage('Yes is selected');
ss:=dir+s;
if deleteFile(ss) then ; // showmessage(ss);

repeat
 fn:=findNext(fl);
 if fn=0 then
 begin
  s:=fl.Name;
//  showmessage(s);
  ss:=dir+s;
  if DeleteFile(ss) then ; // showmessage(ss+' is deleted');
 end;
until fn<>0;

//showmessage('Files related to previous calculations are deleted');

end; // deleting previous files

end; // ff=0
end; // not model is loaded

assign(r,dir+'#r.txt'); rewrite(r);
assign(a,dir+'#a.txt'); rewrite(a);

writeln(a,'This file contains average values for statistical characteristics which were obtained');
writeln(a,'in ',Form1.edit24.text,' probes of the Monte Carlo optimization');
writeln(a,'SMILES taken from file ',form1.edit1.text);
writeln(a,'Method taken from file ',form1.edit19.text);

writeln(a);

if form1.CheckBox21.Checked then
writeln(a,'SMILES is used for the model');
if form1.CheckBox30.Checked then
writeln(a,'Hydrogen suppressed graph (HSG) is used for the model');
if form1.CheckBox29.Checked then
writeln(a,'Hydrogen filled graph (HFG) is used for the model');
if form1.CheckBox31.Checked then
writeln(a,'Graph of Atomic Orbitals (GAO) for used in the model');


writeln(a,'Threshold from ',form1.edit22.text,' to ',form1.edit23.text);
writeln(a);
writeln(a,'n is the number of compounds in set;');
writeln(a,'r is Correlation coefficient;');
writeln(a,'s is standard error of estimation;');
writeln(a,'F is Fischer F-ratio.');
writeln(a,'ns, r2s, ss, and Fs are statistical characteristics of Training set.');
writeln(a,'nc, r2c, sc, and Fc are statistical characteristics of invisible-Training set.');
writeln(a,'nt, r2t, st, and Ft are statistical characteristics of calibration set.');
writeln(a);
writeln(a,'CCC is concordance correlation coefficient [1].');
writeln(a,'[1] L. I-Kuei Lin, A Concordance Correlation Coefficient to Evaluate Reproducibility,');
writeln(a,'Biometrics, 45(1)(1989) 255-268');
writeln(a);
writeln(a,'Rm2av is the average of Rm2 metric, it should be > 0.5 [2]');
writeln(a,'[2] PK Ojha,I Mitra, RN Das,K Roy,Further exploring rm2 metrics for validation of QSPR models,');
writeln(a,'Chemometrics and Intelligent Laboratory Systems, 107(1) (2011) 194-205');
writeln(a);
writeln(a,'IIC is the Index of ideality of correlation [3]');
writeln(a,'[3]AP Toropova, AA Toropov, The index of ideality of correlation: ');
writeln(a,'A criterion of predictability of QSAR models for skin permeability?');
writeln(a,'Science of The Total Environment, 586 (2017) 466-472');
writeln(a);
Writeln(a,'Number of epochs of optimization is ',Form1.edit9.text);
Writeln(a,'Number of probes of optimization is ',Form1.edit24.text);
if form1.RadioButton1.Checked then
writeln(a,'Weight for dr in balance of correlations is ', Form1.edit43.text);


writeln(a,'Start step of the optimization is ',Form1.edit20.text,'*CW(SA)');
writeln(a,'Precision of the optimization is ',Form1.edit21.text,'*CW(SA)');
writeln(a,'CW(SA) is weight of SA at the start');
writeln(a);
Writeln(a,'N111 is the number of SA which take place in training, ');
Writeln(a,'in invisible training, and in calibration sets');
Writeln(a,'W% is ratio of N111/(number of all SA)');
Writeln(a,'N110 is number of SA which take place in Training and invisible-Training');
Writeln(a,'N101 is number of SA which take place in Training and calibration');
Writeln(a,'N100 is number of SA which take place in Training (only)');
writeln(a);

writeln(a,'Model ');

if form1.CheckBox32.Checked then     // GRAPH...
begin
writeln(a,'Involves from graph:');
If form1.checkBox9.checked  then writeln(a,'EC0');
If form1.checkBox28.checked then writeln(a,'EC1');
If form1.checkBox18.checked then writeln(a,'EC2');
If form1.checkBox10.checked then writeln(a,'EC3');
If form1.checkBox6.checked  then writeln(a,'pt2');
If form1.checkBox12.checked then writeln(a,'pt3');
If form1.checkBox13.checked then writeln(a,'vs2');
//If form1.checkBox11.checked then writeln(a,'vs3');
If form1.checkBox20.checked then writeln(a,'NNC');
If form1.checkBox4.checked  then writeln(a,'C7');
If form1.checkBox19.checked then writeln(a,'C6');
If form1.checkBox16.checked then writeln(a,'C5');
If form1.checkBox8.checked  then writeln(a,'C4');
If form1.checkBox5.checked  then writeln(a,'C3');

end;

if form1.CheckBox21.Checked then      // SMILES
begin
writeln(a,'Involves from SMILES:');
If form1.checkBox1.checked  then writeln(a,'S(k)');
If form1.checkBox2.checked  then writeln(a,'SS(k)');
If form1.checkBox3.checked  then writeln(a,'SSS(k)');
If form1.checkBox22.checked then writeln(a,'NOSP');
If form1.checkBox23.checked then writeln(a,'HALO');
If form1.checkBox25.checked then writeln(a,'BOND');
If form1.checkBox27.checked then writeln(a,'HARD');
If form1.checkBox11.checked then writeln(a,'PAIR');
end;

If form1.checkBox17.checked then writeln(a,'Model is classification');

if form1.RadioButton1.Checked
then
begin
writeln(a,'Balance of correlations i.e. Training-Invisible training-Calibration system');
writeln(a,'The dr-weight is ', Form1.edit43.text);
end
else
writeln(a,'Traditional scheme i.e. Training-Calibration system');

writeln(a);
writeln(a);

writeln(r,'This file contains values for statistical characteristics which were obtained');
writeln(r,'in ',Form1.edit24.text,' probes of the Monte Carlo optimization');
writeln(r,'SMILES taken from file ',form1.edit1.text);
writeln(r,'Method taken from file ',form1.edit19.text);

writeln(r);

if form1.CheckBox21.Checked then
writeln(r,'SMILES is used in this model');
if form1.CheckBox30.Checked then
writeln(r,'Hydrogen suppressed graph (HSG) is used in this model');
if form1.CheckBox29.Checked then
writeln(r,'Hydrogen filled graph (HFG) is used in this model');
if form1.CheckBox31.Checked then
writeln(r,'Graph of Atomic Orbitals (GAO) is used in this model');

writeln(r);
writeln(r,'The n is the number of compounds in set;');
writeln(r,'The r is Correlation coefficient;');
writeln(r,'The s is standard error of estimation;');
writeln(r,'The F is Fischer F-ratio.');
writeln(r,'The ns, r2s, ss, and Fs are statistical characteristics of training set.');
writeln(r,'The nc, r2c, sc, and Fc are statistical characteristics of invisible training set.');
writeln(r,'The nt, r2t, st, and Ft are statistical characteristics of calibration set.');

writeln(r,'The Rm2 metric should be > 0.5 [1]');
writeln(r,'[1] PK Ojha,I Mitra, RN Das,K Roy,Chemometr Intell Lab 107(2011)194-205]');

Writeln(r,'The number of epochs of optimization is ',Form1.edit9.text);
Writeln(r,'The number of probes of optimization is ',Form1.edit24.text);
writeln(r,'The threshold (Thrshd) from ',form1.edit22.text,' to ',form1.edit23.text);

writeln(r,'Start step of the optimization is ',Form1.edit20.text,'*CW(SA)');
writeln(r,'Precision of the optimization is ',Form1.edit21.text,'*CW(SA)');
writeln(r,'CW(SA) is weight of SA at the start');
writeln(r);

writeln(r,'Model ');


if form1.CheckBox32.Checked then     // GRAPH...
begin
writeln(r,'Involves from graph:');
If form1.checkBox9.checked  then writeln(r,'EC0');
If form1.checkBox28.checked then writeln(r,'EC1');
If form1.checkBox18.checked then writeln(r,'EC2');
If form1.checkBox10.checked then writeln(r,'EC3');
If form1.checkBox6.checked  then writeln(r,'pt2');
If form1.checkBox12.checked then writeln(r,'pt3');
If form1.checkBox13.checked then writeln(r,'vs2');
//If form1.checkBox11.checked then writeln(r,'vs3');
If form1.checkBox20.checked then writeln(r,'NNC');
If form1.checkBox4.checked  then writeln(r,'C7');
If form1.checkBox19.checked then writeln(r,'C6');
If form1.checkBox16.checked then writeln(r,'C5');
If form1.checkBox8.checked  then writeln(r,'C4');
If form1.checkBox5.checked  then writeln(r,'C3');

end;

if form1.CheckBox21.Checked then      // SMILES
begin
writeln(r,'Involves from SMILES:');
If form1.checkBox1.checked  then writeln(r,'S(k)');
If form1.checkBox2.checked  then writeln(r,'SS(k)');
If form1.checkBox3.checked  then writeln(r,'SSS(k)');
If form1.checkBox22.checked then writeln(r,'NOSP');
If form1.checkBox23.checked then writeln(r,'HALO');
If form1.checkBox25.checked then writeln(r,'BOND');
If form1.checkBox27.checked then writeln(r,'HARD');
If form1.checkBox11.checked then writeln(r,'PAIR');
end;

If form1.checkBox17.checked then writeln(r,'Model is classification');

if form1.RadioButton1.Checked
then
begin
writeln(r,'Balance of correlations i.e. Training-Invisible training-Calibration system');
writeln(r,'The dr-weight is ', Form1.edit43.text);
end
else
writeln(r,'Traditional scheme i.e. Training-Calibration system');

writeln(r);

if form1.CheckBox21.Checked then
If (not form1.checkBox1.checked)  and
   (not form1.checkBox2.checked)  and
   (not form1.checkBox3.checked)  and
   (not form1.checkBox22.checked) and
   (not form1.checkBox23.checked) and

   (not form1.checkBox27.checked) and
   (not form1.checkBox11.checked) and
   (not form1.checkBox44.checked) and
   (not form1.checkBox25.checked)
   then
   begin
    showmessage
 ('The Monte Carlo method optimization is impossible:' + #13 +
  'at least one kind of SMILES attributes (which contain one-, or two-, or three elements)'+#13+
  'should be involved in the modelling');
  halt;
   end; // -s and -ss and -sss !!!

if  form1.CheckBox32.Checked then
If not
   (
   (form1.checkBox9.checked ) or
   (form1.checkBox28.checked) or
   (form1.checkBox18.checked) or
   (form1.checkBox10.checked) or
   (form1.checkBox6.checked ) or
   (form1.checkBox12.checked) or
   (form1.checkBox13.checked) or
( form1.checkBox38.checked ) or // p2 nn
( form1.checkBox39.checked ) or //

( form1.checkBox40.checked ) or //
( form1.checkBox41.checked ) or //
( form1.checkBox42.checked ) or //
( form1.checkBox43.checked ) or //
( form1.checkBox44.checked ) or //
( form1.checkBox45.checked ) or //
( form1.checkBox46.checked ) or //
( form1.checkBox47.checked ) or //
( form1.checkBox48.checked ) or //
( form1.checkBox49.checked ) or //
( form1.checkBox50.checked ) or //

( form1.checkBox51.checked ) or //
( form1.checkBox52.checked ) or //
( form1.checkBox53.checked ) or //
( form1.checkBox54.checked ) or //
( form1.checkBox55.checked ) or //
( form1.checkBox56.checked ) or //
( form1.checkBox57.checked ) or //
( form1.checkBox58.checked ) or //
( form1.checkBox59.checked ) or //
( form1.checkBox60.checked ) or //

( form1.checkBox61.checked ) or //
( form1.checkBox62.checked ) or //
( form1.checkBox63.checked ) or //
( form1.checkBox64.checked ) or //
( form1.checkBox65.checked ) or //
( form1.checkBox66.checked ) or //
( form1.checkBox67.checked ) or //
( form1.checkBox68.checked ) or //
( form1.checkBox69.checked ) or //
( form1.checkBox70.checked ) or //

( form1.checkBox71.checked ) or //
( form1.checkBox72.checked ) or //
( form1.checkBox73.checked ) or //
( form1.checkBox74.checked ) or //
( form1.checkBox75.checked ) or //
( form1.checkBox76.checked ) or //
( form1.checkBox77.checked ) or //
( form1.checkBox78.checked ) or //
( form1.checkBox79.checked ) or //
( form1.checkBox80.checked ) or //

( form1.checkBox81.checked ) or //
( form1.checkBox82.checked ) or //
( form1.checkBox83.checked ) or //
( form1.checkBox84.checked ) or //
( form1.checkBox85.checked ) or //
( form1.checkBox86.checked ) or //
( form1.checkBox87.checked ) or //
( form1.checkBox88.checked ) or //
( form1.checkBox89.checked ) or //
( form1.checkBox90.checked ) or //

( form1.checkBox91.checked ) or //
( form1.checkBox92.checked ) or //
( form1.checkBox93.checked ) or //
( form1.checkBox94.checked ) or //
( form1.checkBox95.checked ) or //
( form1.checkBox96.checked ) or //
( form1.checkBox97.checked ) or //
( form1.checkBox98.checked ) or //
( form1.checkBox99.checked ) or //
( form1.checkBox100.checked ) or //

( form1.checkBox101.checked ) or //
( form1.checkBox102.checked ) or //
( form1.checkBox103.checked ) or //
( form1.checkBox104.checked ) or //
( form1.checkBox105.checked ) or //
( form1.checkBox106.checked ) or //
( form1.checkBox107.checked ) or //
( form1.checkBox108.checked ) or //
( form1.checkBox109.checked ) or //
( form1.checkBox110.checked ) or //

( form1.checkBox111.checked ) or //
( form1.checkBox112.checked ) or //
( form1.checkBox113.checked ) or //
( form1.checkBox114.checked ) or //
( form1.checkBox115.checked ) or //
( form1.checkBox116.checked ) or //
( form1.checkBox117.checked ) or //
( form1.checkBox118.checked ) or //
( form1.checkBox119.checked ) or //
( form1.checkBox120.checked ) or //

( form1.checkBox121.checked ) or //
( form1.checkBox122.checked ) or //
( form1.checkBox123.checked ) or //
( form1.checkBox124.checked ) or //
( form1.checkBox125.checked ) or //
( form1.checkBox126.checked ) or //
( form1.checkBox127.checked ) or //
( form1.checkBox128.checked ) or //
( form1.checkBox129.checked ) or //
( form1.checkBox130.checked ) or //

( form1.checkBox131.checked ) or //
( form1.checkBox132.checked ) or //
( form1.checkBox133.checked ) or //
( form1.checkBox134.checked ) or //
( form1.checkBox135.checked ) or //
( form1.checkBox136.checked ) or //
( form1.checkBox137.checked ) or //


   (form1.checkBox4.checked)  or
   (form1.checkBox19.checked) or
   (form1.checkBox16.checked) or
   (form1.checkBox8.checked)  or
   (form1.checkBox5.checked)  or
//   (form1.checkBox11.checked) or
   (form1.checkBox20.checked)
   )
   then
   begin
    showmessage
 ('The Monte Carlo method optimization is impossible:' + #13 +
  '          at least one kind of graph-invariants '+#13+
  '           should be involved in the modelling');
  halt;
   end; // EC0, EC1, ... EC3 are absent


writeln(r);

// hybrid indices

writeln(r);

writeln(r,
'Trshd:',
'Nact :',
'Probe:',
'  ns :',
'         rs2:',
'       ss :',
'    fs :',
'  nc :',
'         rc2:',
'       sc :',
'    fc :',
'  nt :',
'         rt2:',
'       st :',
'    ft :',
'    Rm2');

writeln(a,
'Trshd:',
'Nact :',
//'Probe:',

'  ns :',
'         rs2:',
'       ss :',
'    fs :',

'  nc :',
'         rc2:',
'       sc :',
'    fc :',

'  nt :',
'         rt2:',
'       st :',
'    ft :',
'      CCC   :',
'      Rm2av :',
'      IIC   :',
' W% :',
'N111:',
'N110:',
'N101:',
'N100:',
' SplitDefect:',
'NormSpltDef'
);

// if limn0=limne then begin dir:='model/'; probe:=1 end else dir:='search/';

//CharmName:='#Charm.txt';
//Assign(Charm,CharMname);
//Rewrite(Charm);

(*

writeln(Charm,
'  Threshold :',
'   Rtrn     :',
'   Rclb     :',
'   Rtst     :',
' ATRN+      :',
' ACLB+      :',
' ATST+      :',
' ATRN-      :',
' ACLB-      :',
' ATST-      :'
);

*)


for limni:=limn0 to limne   do        // The threshold...
begin

if dir='search/'
then
begin
   if not onlyFirst then
   form1.Label24.Caption:=
   'Threshold...........'+inttostr(limni)+' to '+inttostr(limne)
   else
   begin
   form1.Label24.Caption:=
   'Threshold...........'+inttostr(limni)+' to '+inttostr(limni);
   form1.Edit23.Text:=IntToStr(limni);
   end
end
else
form1.Label24.Caption:=
'Selected threshold is '+inttostr(limni);


art:=0.0;
ast:=0.0;
aft:=0.0;
arc:=0.0;
asc:=0.0;
afc:=0.0;
are:=0.0;
ase:=0.0;
afe:=0.0;
Rm2av:=0.0;
// ini average



for probe:=1     to nprobes do       // The probe
begin

Restart:

Total_best_TST_r:=0.0;  best_r2_TST:=0.0;
Total_best_TRN_r:=0.0;  best_r2_TRN:=0.0;

Total_best_TST_s:=10000.0;  best_s_TST:=10000.0;
Total_best_TRN_s:=10000.0;  best_S_TRN:=10000.0;

if dir='search/'
then

form1.label13.caption:=
'Probe.................'+inttostr(probe)+' to '+inttostr(nprobes)
else
form1.label13.caption:=
'   ';


sms:=form1.edit1.text;

op:=dir+'opter';
dc:=dir+'d' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // demo dcw calculation
wp:=dir+'Ws' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // Correlation weights
md:=dir+'m' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // model PA=C0+C1*DCW

ec:=dir+'e' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // evolution of correlations
                                                             // TRN CLB TST
id:=dir+'i' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // idealization

//x2:=form1.Edit2.Text;
//x6:=form1.Edit6.Text;
//x7:=form1.Edit7.Text;

//form1.Edit10.Text:=IntToStr(limni);

//form1.Edit2.Text:=op;
//form1.Edit6.Text:=dc;
//form1.Edit7.Text:=md;

if not Model_is_loaded then iniCWs:=True
                       else iniCWs:=False;

opt0(sms,op,wp);

// showmessage('opto is OK');

If form1.CheckBox14.Checked then
begin
assign(rrr,ec);rewrite(rrr);
writeln(rrr,'The evolution of correlations. The R is correlation coefficient; s is standard error');
writeln(rrr,' No.:R2-sub :R2-clb :R2-tst : s-sub   : s-clb   : s-tst');
closefile(rrr);
end;

optimiz(op,ec);

if best_r2_TRN > total_best_TRN_r then
begin
total_best_TRN_r:=best_r2_TRN;
total_best_Probe_TRN_r:=probe;
total_best_Threshold_TRN_r:=limni;
total_best_Nepoch_TRN_r:=best_it_TRN_r;
end;

if best_r2_TST > total_best_TST_r then
begin
total_best_TST_r:=best_r2_TST;
total_best_Probe_TST_r:=probe;
total_best_Threshold_TST_r:=limni;
total_best_Nepoch_TST_r:=best_it_TST_r;
end;

if best_s_TRN < total_best_TRN_s then
begin
total_best_TRN_s:=best_s_TRN;
total_best_Probe_TRN_s:=probe;
total_best_Threshold_TRN_s:=limni;
total_best_Nepoch_TRN_s:=best_it_TRN_s;
end;

if best_s_TST < total_best_TST_s then
begin
total_best_TST_s:=best_s_TST;
total_best_Probe_TST_s:=probe;
total_best_Threshold_TST_s:=limni;
total_best_Nepoch_TST_s:=best_it_TST_s;
end;

R2_TRN_BEST[probe,limni]:=best_r2_TRN;
NEPOCH_BEST_TRN_r[probe,limni]:=best_it_TRN_r;

R2_TST_BEST[probe,limni]:=best_r2_TST;
NEPOCH_BEST_TST_r[probe,limni]:=best_it_TST_r;

S_TRN_BEST[probe,limni]:=best_s_TRN;
NEPOCH_BEST_TRN_s[probe,limni]:=best_it_TRN_s;

S_TST_BEST[probe,limni]:=best_s_TST;
NEPOCH_BEST_TST_s[probe,limni]:=best_it_TST_s;


IniCWs:=False;

saveOptimizMatrix(op,wp);
if form1.CheckBox15.checked then demoDCW(dc);
MDL(md,'y');
MDL(md,'n');

//Idealization(id,test,dcw,pa);

//if not nnoprint then begin nno_print; nnoprint:=true; end;

form1.Edit2.Text:=x2;
form1.Edit6.Text:=x6;
form1.Edit7.Text:=x7;

// showmessage('next operation...');

rt:=sqr(kfkr(Train,DCW,PA,types,nt));
rc:=sqr(kfkr(Calib,DCW,PA,types,nc));
re:=sqr(kfkr(Test ,DCW,PA,types,ne));


rt05:=sqrt(rt);
rc05:=sqrt(rc);
re05:=sqrt(re);

ft:=Fischer_PA_c0_c1_DCW(rt05,nt);
fc:=Fischer_PA_c0_c1_DCW(rc05,nc);
fe:=Fischer_PA_c0_c1_DCW(re05,ne);

c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1 );
//c0c1(Test ,DCW,PA,c00,c11,dc00,dc11);

st:=see(Train,c0,c1);
sc:=see(Calib,c0,c1);
se:=see(Test ,c0,c1);


writeln(r,
limNI:5,':',
NactSFk:5,':',
Probe:5,':',

nt:5,':',
rt:FR1:FR2,':',
st:FS1:FS2,':',
ft:7:0,':',

nc:5,':',
rc:FR1:FR2,':',
sc:FS1:FS2,':',
fc:7:0,':',

ne:5,':',
re:FR1:FR2,':',
se:FS1:FS2,':',
fe:7:0,':',
Rm2:FR1:FR2

);

art:=art + rt;
ast:=ast + st;
aft:=aft + ft;

arc:=arc + rc;
asc:=asc + sc;
afc:=afc + fc;

are:=are + re;
ase:=ase + se;
afe:=afe + fe;

rm2av:=rm2av + rm2;

// MDL(md,'n');


end; // probe

art:=art/nprobes;
ast:=ast/nprobes;
aft:=aft/nprobes;

arc:=arc/nprobes;
asc:=asc/nprobes;
afc:=afc/nprobes;

are:=are/nprobes;
ase:=ase/nprobes;
afe:=afe/nprobes;

rm2av:=rm2av/nprobes;

defect:= StrToFloat(form1.Edit35.text);
Nact:=NactSFk;

(*
showmessage
(
' Defect='+FloatToStrF(defect,FFfixed,9,4)+
' Nact ='+FloatToStrF(Nact,FFfixed,9,0)+
' T='+IntToStr(limni)
);
*)

//NormSpltDef:=( ( defect*limni)/Nact )* xiny(limni,0.33333333);
//NormSpltDef:= ( defect*xiny(limni,1.3333333) / Nact );

//NormSpltDef:= ( defect*xiny(limni,solomon) / Nact );
//NormSpltDef:= ( defect / Nact );

form1.Edit2.Text:=FloatToStrF(density,FFfixed,7,3);

writeln(a,
limNI:5,':',
NactSFk:5,':',
//'     :',
nt:5,':',
art:FR1:FR2,':',
ast:FS1:FS2,':',
aft:7:0,':',

nc:5,':',
arc:FR1:FR2,':',
asc:FS1:FS2,':',
afc:7:0,':',

ne:5,':',
are:FR1:FR2,':',
ase:FS1:FS2,':',
afe:7:0,':',
ccc(calib,dcw,pa,types,nccc):FR1:FR2,':',
rm2av:FR1:FR2,':',
IIC_autonom(calib,c0,c1,dcw,pa,types):FR1:FR2,':',
strToInt(form1.edit36.text):4,':',
strToInt(form1.edit13.text):4,':',
strToInt(form1.edit12.text):4,':',
strToInt(form1.edit8.text) :4,':',
strToInt(form1.edit32.text):4,':',
StrToFloat(form1.Edit35.text):12:5,':',
NormSpltDef:11:5
);

writeln(r,
limNI:5,':',
'     :',
'     :',

'     :',
art:FR1:FR2,':',
ast:FS1:FS2,':',
aft:7:0,':',

'     :',
arc:FR1:FR2,':',
asc:FS1:FS2,':',
afc:7:0,':',
'     :',
are:FR1:FR2,':',
ase:FS1:FS2,':',
afe:7:0,':',
Rm2av:FR1:FR2
);

if dir='search/' then SaveProbeStatOrder(limNI,limni);

if onlyFirsT then goto onlys1;


end; // limNI

onlys1:

series:='n';

closefile(r);
closefile(a);
// closefile(Charm);

assignfile(r,'search/#BestMDL.txt');
rewrite(r);

writeln(r,'Data from ',form1.edit1.text);
writeln(r,'Representation of molecular structure by ');
// if form1.checkBox32.Checked

begin
if form1.checkBox30.Checked then writeln(r,'* Hydrogen suppresed graph');
if form1.checkBox29.Checked then writeln(r,'* Hydrogen filled graph');
if form1.checkBox31.Checked then writeln(r,'* Graph of atomic orbitals');
end;

if form1.checkBox21.Checked then
writeln(r,'* SMILES');
writeln(r);

Writeln(r,'Correlation coefficients for the Active TRAINING SET');

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+R2_TRN_BEST[probe,limni];
write(r,R2_TRN_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( R2_TRN_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);

writeln(r,sum1:10:4,':',sum2:10:4 );
end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the active TRAINING SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TRN_r[probe,limni];
write(r,NEPOCH_BEST_TRN_r[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TRN_r[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

Writeln(r);
//////////////////////////////////////// TRAIN R N*

Writeln(r,'Correlation coefficients for the passive Training SET');

maxRtst:=-10.0;

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+R2_TST_BEST[probe,limni];
write(r,R2_TST_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;

if sum1>maxRtst then
begin
maxRtst:=sum1;
bestT_R2:=limni;
end; // sum1 > maxRtst

sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( R2_TST_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);

write(r,sum1:10:4,':',sum2:10:4 );

//write(r,splitdefect[limni]:9:5);

writeln(r);

end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the passive training SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TST_r[probe,limni];
write(r,NEPOCH_BEST_TST_r[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;

if limni=BestT_R2 then BestN_R2:=sum1;

sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TST_r[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

Writeln(r);
//////////////////////////////////////// TEST R N*

writeln(r);
Writeln(r,'Preferable threshold T*=',BestT_R2,'  Preferable average number of epochs   N*=',BestN_R2:5:1,'   Average R2 for calibration set =',maxRtst:9:4);
writeln(r);


Writeln(r,'Root-mean-square error for the active TRAINING SET');

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+S_TRN_BEST[probe,limni];
write(r,S_TRN_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( S_TRN_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);

writeln(r,sum1:10:4,':',sum2:10:4 );
end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the active TRAINING SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TRN_s[probe,limni];
write(r,NEPOCH_BEST_TRN_s[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TRN_s[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

Writeln(r);
//////////////////////////////////////// TRAIN S N*

MinRMSE:=100000000000.0;

Writeln(r,'Root-mean-square error for the passive training SET');

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+S_TST_BEST[probe,limni];
write(r,S_TST_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;

if sum1<MinRMSE then
begin
MinRMSE:=sum1;
bestT_RMSE:=limni;
end; // sum1 > maxRtst


sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( S_TST_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);



writeln(r,sum1:10:4,':',sum2:10:4 );
end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the passive training SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TST_s[probe,limni];
write(r,NEPOCH_BEST_TST_s[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;

if limni=BestT_RMSE then BestN_RMSE:=sum1;


sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TST_s[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

//////////////////////////////////////// TEST S N*

writeln(r);
Writeln(r,'Preferable threshold T*=',BestT_RMSE,'  Preferable average number of epochs   N*=',BestN_RMSE:5:1,'   Average RMSE for calibration set =',MinRMSE:9:4);
writeln(r);

writeln(r,'IMPORTANT:');
writeln(r,'Ideal result if the preferable threshold is the same for correlation');
writeln(r,'coefficient of the calibration set and for root-mean-square error of the calibration set.');
writeln(r,'If they are different, the threshold that gives the best correlation coefficient');
writeln(r,'should be choice.');


closefile(r);

repeat
      defineRecFile(delme);
      if delme<>'No' then deletefile(delme);
until delme='No';


RecommFileName:=
'#Recommended T'
+IntToStr(BestT_R2)
+' and N'
+FloatToStrF(BestN_R2,FFfixed,5,0)
+'.txt';

assign(r,RecommFileName);
rewrite(r);
Writeln(r,'The search for the best correlation coefficient (R2) for the calibration set:');
writeln(r,'Preferable threshold T*=',BestT_R2,'  Preferable average number of epochs   N*=',BestN_R2:5:1,  '   Average R2   for calibration set =',maxRtst:9:4);

closefile(r);

deletefile(dir+'opter');

SAS:=true; // April5,2024

end;     // auto = authomatic : limM and Probes

procedure auto2;
Label
    Restart, onlys1;
var
    CharmName,          // Characteristics of models TRN_Alpha_plus, etc.
    x2,x6,x7,
    mss,     // message
    sms,     // sms for external DCW calculation ???
    op,      // optimization data
    wp,      // work???
    dc,      // descriptor calculation
    md,      // model
    ec,      // file of evolution of correlations
    id       // idealization = del worst outlier, del worst outlier ... 5 times
    :string;
    limn0, limne, nprobes, rr:integer;
                        // R-TRN, R'-CLB, R''-TST
    CharM,              // Charm = Threshold-R-R'-R''-TRN_Alpha_plus-...
    a,r,rrr:text;
                        // TRN training, CLB calibration, TST test
    A12,A13,A23,        // prevalence SAk in TRN-CLB A12
                        //                   TRN-TST A13
                        //                   CLB-TST A23
    c0,c1, dc0,dc1,

    rt05,rc05,re05,

    rt,st,ft,
    rc,sc,fc,
    re,se,fe:            real;

    nt,nc,ne:            integer;

    Rm2av,
    art,ast,aft,
    arc,asc,afc,
    are,ase,afe:         real;
               // Formats:
    fr1,fr2,   // R
    fs1,fs2,   // S
//    fd1,fd2,   // DCW
    k:integer;
    nnoprint:boolean;
    s:string;
    fl:TSearchRec;
    ss,
    dirr:string;
    ff, fn,
    d:integer;
    txt:string;
    nf, // fantom to calulate kfkrw
    sa:integer;

    TRN_CLB_max_plus,

    TRN_max_alpha_minus,
    TRN_max_alpha_plus ,
    CLB_max_alpha_minus,
    CLB_max_alpha_plus ,
    TST_max_alpha_minus,
    TST_max_alpha_plus :real;

    t:integer;

    sum1,sum2:real;

    BestN_R2,      //
    BestN_RMSE,
    minRMSE,       // minimal RMSE for test set
    maxRtst:real;  // maximal correlation coefficient for test set
    BestT_RMSE,
    BestT_R2:integer; // T* for the search
    delme:string; // for delete old recommend T and N .txt

    defect:real; // split defect = P - P' / N - N'
    Nact:real;   // number of active attributes
    NormSpltDef:real; // normalized defect = [ (defect * T) / Nact ]* T^(1/3)
    nccc:integer; // to calculate CCC
    copyR2C:real; // test print R2C April9,2024

begin



assign(FYI,'!FYI.txt');
rewrite(FYI);

writeln(FYI,
'Epoch:',
'      W%  :',
'     N111 :',
'     N110 :',
'     N101 :',
'     N100 :',
'     Nall :',
'   DEFECT :',
'  CCCP(C) :',
'     R2A  :',
'     R2P  :',
'     R2C  :',
'     R2V  :',
' Best R2C :',
' Best ID ');



//if model_is_loaded then showmessage('Model is loaded')
//                   else showmessage('Model is not loaded');

form1.Button28.visible:=false;
form1.Button29.visible:=false;
//form1.Edit50.visible:=false;

nnoprint:=false;

FR1:=StrToInt(form1.edit26.text); // format R
FR2:=StrToInt(form1.edit27.text);
Fs1:=StrToInt(form1.edit28.text); // format s
Fs2:=StrToInt(form1.edit29.text);

// jan 29, 2018
FR1:=12; FR2:=4;
FS1:=10; FS2:=3;
//ffd:=StrToInt(form1.edit30.text); // format DCW:12:fd
//Fp :=StrToInt(form1.edit31.text); // format PA:12:fp

dCweight:=StrToFloat(Form1.Edit38.Text); // weight for Index of correlation confidence Nov1, 2019
dRweight:=StrToFloat(Form1.Edit43.Text);
dKweight:=StrToFloat(Form1.Edit10.Text);

series:='y';

limn0  :=StrToInt(form1.Edit22.Text);
limnE  :=StrToInt(form1.Edit23.Text);
nprobes:=StrToInt(form1.Edit24.Text);

if limn0=limne then
begin dir:='model/';
//probe:=1
end
else
begin
dir:='search/';
form1.Button10.Visible:=false;
form1.Label19.Visible:=true;
end; // model/  else


deletefiles('search/');
deletefiles('model/');

assign(r,dir+'#r.txt'); rewrite(r);
assign(a,dir+'#a.txt'); rewrite(a);

writeln(a,'This file contains average values for statistical characteristics which were obtained');
writeln(a,'in ',Form1.edit24.text,' probes of the Monte Carlo optimization');
writeln(a,'SMILES taken from file ',form1.edit1.text);
writeln(a,'Method taken from file ',form1.edit19.text);

writeln(a);

if form1.CheckBox21.Checked then
writeln(a,'SMILES is used for the model');
if form1.CheckBox30.Checked then
writeln(a,'Hydrogen suppressed graph (HSG) is used for the model');
if form1.CheckBox29.Checked then
writeln(a,'Hydrogen filled graph (HFG) is used for the model');
if form1.CheckBox31.Checked then
writeln(a,'Graph of Atomic Orbitals (GAO) for used in the model');


writeln(a,'Threshold from ',form1.edit22.text,' to ',form1.edit23.text);
writeln(a);
writeln(a,'n is the number of compounds in set;');
writeln(a,'r is Correlation coefficient;');
writeln(a,'s is standard error of estimation;');
writeln(a,'F is Fischer F-ratio.');
writeln(a,'ns, r2s, ss, and Fs are statistical characteristics of Training set.');
writeln(a,'nc, r2c, sc, and Fc are statistical characteristics of invisible-Training set.');
writeln(a,'nt, r2t, st, and Ft are statistical characteristics of calibration set.');
writeln(a);
writeln(a,'CCC is concordance correlation coefficient [1].');
writeln(a,'[1] L. I-Kuei Lin, A Concordance Correlation Coefficient to Evaluate Reproducibility,');
writeln(a,'Biometrics, 45(1)(1989) 255-268');
writeln(a);
writeln(a,'Rm2av is the average of Rm2 metric, it should be > 0.5 [2]');
writeln(a,'[2] PK Ojha,I Mitra, RN Das,K Roy,Further exploring rm2 metrics for validation of QSPR models,');
writeln(a,'Chemometrics and Intelligent Laboratory Systems, 107(1) (2011) 194-205');
writeln(a);
writeln(a,'IIC is the Index of ideality of correlation [3]');
writeln(a,'[3]AP Toropova, AA Toropov, The index of ideality of correlation: ');
writeln(a,'A criterion of predictability of QSAR models for skin permeability?');
writeln(a,'Science of The Total Environment, 586 (2017) 466-472');
writeln(a);
Writeln(a,'Number of epochs of optimization is ',Form1.edit9.text);
Writeln(a,'Number of probes of optimization is ',Form1.edit24.text);
if form1.RadioButton1.Checked then
writeln(a,'Weight for dr in balance of correlations is ', Form1.edit43.text);
if form1.CheckBox24.Checked then
writeln(a,'Weight for S-Ideality index is ',Form1.edit42.text);

writeln(a,'Start step of the optimization is ',Form1.edit20.text,'*CW(SA)');
writeln(a,'Precision of the optimization is ',Form1.edit21.text,'*CW(SA)');
writeln(a,'CW(SA) is weight of SA at the start');
writeln(a);
Writeln(a,'N111 is the number of SA which take place in training, ');
Writeln(a,'in invisible training, and in calibration sets');
Writeln(a,'W% is ratio of N111/(number of all SA)');
Writeln(a,'N110 is number of SA which take place in Training and invisible-Training');
Writeln(a,'N101 is number of SA which take place in Training and calibration');
Writeln(a,'N100 is number of SA which take place in Training (only)');
writeln(a);

//if form1.RadioButton2.Checked then form1.checkBox24.checked:=False;

writeln(a,'Model ');

if form1.CheckBox32.Checked then     // GRAPH...
begin
writeln(a,'Involves from graph:');
If form1.checkBox9.checked  then writeln(a,'EC0');
If form1.checkBox28.checked then writeln(a,'EC1');
If form1.checkBox18.checked then writeln(a,'EC2');
If form1.checkBox10.checked then writeln(a,'EC3');
If form1.checkBox6.checked  then writeln(a,'pt2');
If form1.checkBox12.checked then writeln(a,'pt3');
If form1.checkBox13.checked then writeln(a,'vs2');
If form1.checkBox37.checked then writeln(a,'vs3');
If form1.checkBox20.checked then writeln(a,'NNC');
If form1.checkBox4.checked  then writeln(a,'C7');
If form1.checkBox19.checked then writeln(a,'C6');
If form1.checkBox16.checked then writeln(a,'C5');
If form1.checkBox8.checked  then writeln(a,'C4');
If form1.checkBox5.checked  then writeln(a,'C3');

end;

if form1.CheckBox21.Checked then      // SMILES
begin
writeln(a,'Involves from SMILES:');
If form1.checkBox1.checked  then writeln(a,'S(k)');
If form1.checkBox2.checked  then writeln(a,'SS(k)');
If form1.checkBox3.checked  then writeln(a,'SSS(k)');
If form1.checkBox22.checked then writeln(a,'NOSP');
If form1.checkBox23.checked then writeln(a,'HALO');
If form1.checkBox25.checked then writeln(a,'BOND');
If form1.checkBox27.checked then writeln(a,'HARD');
If form1.checkBox11.checked then writeln(a,'PAIR');
end;

If form1.checkBox17.checked then writeln(a,'Model is classification');

if form1.RadioButton1.Checked
then
begin
writeln(a,'Balance of correlations i.e. Training-Invisible training-Calibration system');
writeln(a,'The dr-weight is ', Form1.edit43.text);
end
else
writeln(a,'Traditional scheme i.e. Training-Calibration system');
(*
If (form1.checkBox24.checked) // or (form1.checkBox26.checked)
then
begin
writeln(a,'with ideal slopes');
If (form1.checkBox24.checked) then writeln(a,'c0,c1 criterion is involved');
If (form1.checkBox24.checked) then writeln(a,'The dC-weight is ',Form1.edit42.text);
end;
*)
writeln(a);
writeln(a);

writeln(r,'This file contains values for statistical characteristics which were obtained');
writeln(r,'in ',Form1.edit24.text,' probes of the Monte Carlo optimization');
writeln(r,'SMILES taken from file ',form1.edit1.text);
writeln(r,'Method taken from file ',form1.edit19.text);

writeln(r);

if form1.CheckBox21.Checked then
writeln(r,'SMILES is used in this model');
if form1.CheckBox30.Checked then
writeln(r,'Hydrogen suppressed graph (HSG) is used in this model');
if form1.CheckBox29.Checked then
writeln(r,'Hydrogen filled graph (HFG) is used in this model');
if form1.CheckBox31.Checked then
writeln(r,'Graph of Atomic Orbitals (GAO) is used in this model');

writeln(r);
writeln(r,'The n is the number of compounds in set;');
writeln(r,'The r is Correlation coefficient;');
writeln(r,'The s is standard error of estimation;');
writeln(r,'The F is Fischer F-ratio.');
writeln(r,'The ns, r2s, ss, and Fs are statistical characteristics of training set.');
writeln(r,'The nc, r2c, sc, and Fc are statistical characteristics of invisible training set.');
writeln(r,'The nt, r2t, st, and Ft are statistical characteristics of calibration set.');

writeln(r,'The Rm2 metric should be > 0.5 [1]');
writeln(r,'[1] PK Ojha,I Mitra, RN Das,K Roy,Chemometr Intell Lab 107(2011)194-205]');

Writeln(r,'The number of epochs of optimization is ',Form1.edit9.text);
Writeln(r,'The number of probes of optimization is ',Form1.edit24.text);
writeln(r,'The threshold (Thrshd) from ',form1.edit22.text,' to ',form1.edit23.text);

writeln(r,'Start step of the optimization is ',Form1.edit20.text,'*CW(SA)');
writeln(r,'Precision of the optimization is ',Form1.edit21.text,'*CW(SA)');
writeln(r,'CW(SA) is weight of SA at the start');
writeln(r);


//if form1.RadioButton2.Checked then form1.checkBox24.checked:=False;

writeln(r,'Model ');


if form1.CheckBox32.Checked then     // GRAPH...
begin
writeln(r,'Involves from graph:');
If form1.checkBox9.checked  then writeln(r,'EC0');
If form1.checkBox28.checked then writeln(r,'EC1');
If form1.checkBox18.checked then writeln(r,'EC2');
If form1.checkBox10.checked then writeln(r,'EC3');
If form1.checkBox6.checked  then writeln(r,'pt2');
If form1.checkBox12.checked then writeln(r,'pt3');
If form1.checkBox13.checked then writeln(r,'vs2');
//If form1.checkBox11.checked then writeln(r,'vs3');
If form1.checkBox20.checked then writeln(r,'NNC');
If form1.checkBox4.checked  then writeln(r,'C7');
If form1.checkBox19.checked then writeln(r,'C6');
If form1.checkBox16.checked then writeln(r,'C5');
If form1.checkBox8.checked  then writeln(r,'C4');
If form1.checkBox5.checked  then writeln(r,'C3');

end;

if form1.CheckBox21.Checked then      // SMILES
begin
writeln(r,'Involves from SMILES:');
If form1.checkBox1.checked  then writeln(r,'S(k)');
If form1.checkBox2.checked  then writeln(r,'SS(k)');
If form1.checkBox3.checked  then writeln(r,'SSS(k)');
If form1.checkBox22.checked then writeln(r,'NOSP');
If form1.checkBox23.checked then writeln(r,'HALO');
If form1.checkBox25.checked then writeln(r,'BOND');
If form1.checkBox27.checked then writeln(r,'HARD');
If form1.checkBox11.checked then writeln(r,'PAIR');
end;

If form1.checkBox17.checked then writeln(r,'Model is classification');

if form1.RadioButton1.Checked
then
begin
writeln(r,'Balance of correlations i.e. Training-Invisible training-Calibration system');
writeln(r,'The dr-weight is ', Form1.edit43.text);
end
else
writeln(r,'Traditional scheme i.e. Training-Calibration system');
(*
If (form1.checkBox24.checked) // or (form1.checkBox26.checked)
then
begin
writeln(r,'with ideal slopes');
If (form1.checkBox24.checked) then writeln(r,'c0-c1 criterion is involved');
writeln(r,'The dC-weight is ',Form1.edit42.text);
end;
*)
writeln(r);

if form1.CheckBox21.Checked then
If (not form1.checkBox1.checked)  and
   (not form1.checkBox2.checked)  and
   (not form1.checkBox3.checked)  and
   (not form1.checkBox22.checked) and
   (not form1.checkBox23.checked) and

   (not form1.checkBox27.checked) and
   (not form1.checkBox11.checked) and
   (not form1.checkBox44.checked) and
   (not form1.checkBox25.checked)
   then
   begin
    showmessage
 ('The Monte Carlo method optimization is impossible:' + #13 +
  'at least one kind of SMILES attributes (which contain one-, or two-, or three elements)'+#13+
  'should be involved in the modelling');
  halt;
   end; // -s and -ss and -sss !!!

if  form1.CheckBox32.Checked then
If not
   (
   (form1.checkBox9.checked ) or
   (form1.checkBox28.checked) or
   (form1.checkBox18.checked) or
   (form1.checkBox10.checked) or
   (form1.checkBox6.checked ) or
   (form1.checkBox12.checked) or
   (form1.checkBox13.checked) or
( form1.checkBox38.checked ) or // p2 nn
( form1.checkBox39.checked ) or //

( form1.checkBox40.checked ) or //
( form1.checkBox41.checked ) or //
( form1.checkBox42.checked ) or //
( form1.checkBox43.checked ) or //
( form1.checkBox44.checked ) or //
( form1.checkBox45.checked ) or //
( form1.checkBox46.checked ) or //
( form1.checkBox47.checked ) or //
( form1.checkBox48.checked ) or //
( form1.checkBox49.checked ) or //
( form1.checkBox50.checked ) or //

( form1.checkBox51.checked ) or //
( form1.checkBox52.checked ) or //
( form1.checkBox53.checked ) or //
( form1.checkBox54.checked ) or //
( form1.checkBox55.checked ) or //
( form1.checkBox56.checked ) or //
( form1.checkBox57.checked ) or //
( form1.checkBox58.checked ) or //
( form1.checkBox59.checked ) or //
( form1.checkBox60.checked ) or //

( form1.checkBox61.checked ) or //
( form1.checkBox62.checked ) or //
( form1.checkBox63.checked ) or //
( form1.checkBox64.checked ) or //
( form1.checkBox65.checked ) or //
( form1.checkBox66.checked ) or //
( form1.checkBox67.checked ) or //
( form1.checkBox68.checked ) or //
( form1.checkBox69.checked ) or //
( form1.checkBox70.checked ) or //

( form1.checkBox71.checked ) or //
( form1.checkBox72.checked ) or //
( form1.checkBox73.checked ) or //
( form1.checkBox74.checked ) or //
( form1.checkBox75.checked ) or //
( form1.checkBox76.checked ) or //
( form1.checkBox77.checked ) or //
( form1.checkBox78.checked ) or //
( form1.checkBox79.checked ) or //
( form1.checkBox80.checked ) or //

( form1.checkBox81.checked ) or //
( form1.checkBox82.checked ) or //
( form1.checkBox83.checked ) or //
( form1.checkBox84.checked ) or //
( form1.checkBox85.checked ) or //
( form1.checkBox86.checked ) or //
( form1.checkBox87.checked ) or //
( form1.checkBox88.checked ) or //
( form1.checkBox89.checked ) or //
( form1.checkBox90.checked ) or //

( form1.checkBox91.checked ) or //
( form1.checkBox92.checked ) or //
( form1.checkBox93.checked ) or //
( form1.checkBox94.checked ) or //
( form1.checkBox95.checked ) or //
( form1.checkBox96.checked ) or //
( form1.checkBox97.checked ) or //
( form1.checkBox98.checked ) or //
( form1.checkBox99.checked ) or //
( form1.checkBox100.checked ) or //

( form1.checkBox101.checked ) or //
( form1.checkBox102.checked ) or //
( form1.checkBox103.checked ) or //
( form1.checkBox104.checked ) or //
( form1.checkBox105.checked ) or //
( form1.checkBox106.checked ) or //
( form1.checkBox107.checked ) or //
( form1.checkBox108.checked ) or //
( form1.checkBox109.checked ) or //
( form1.checkBox110.checked ) or //

( form1.checkBox111.checked ) or //
( form1.checkBox112.checked ) or //
( form1.checkBox113.checked ) or //
( form1.checkBox114.checked ) or //
( form1.checkBox115.checked ) or //
( form1.checkBox116.checked ) or //
( form1.checkBox117.checked ) or //
( form1.checkBox118.checked ) or //
( form1.checkBox119.checked ) or //
( form1.checkBox120.checked ) or //

( form1.checkBox121.checked ) or //
( form1.checkBox122.checked ) or //
( form1.checkBox123.checked ) or //
( form1.checkBox124.checked ) or //
( form1.checkBox125.checked ) or //
( form1.checkBox126.checked ) or //
( form1.checkBox127.checked ) or //
( form1.checkBox128.checked ) or //
( form1.checkBox129.checked ) or //
( form1.checkBox130.checked ) or //

( form1.checkBox131.checked ) or //
( form1.checkBox132.checked ) or //
( form1.checkBox133.checked ) or //
( form1.checkBox134.checked ) or //
( form1.checkBox135.checked ) or //
( form1.checkBox136.checked ) or //
( form1.checkBox137.checked ) or //


   (form1.checkBox4.checked)  or
   (form1.checkBox19.checked) or
   (form1.checkBox16.checked) or
   (form1.checkBox8.checked)  or
   (form1.checkBox5.checked)  or
//   (form1.checkBox11.checked) or
   (form1.checkBox20.checked)
   )
   then
   begin
    showmessage
 ('The Monte Carlo method optimization is impossible:' + #13 +
  '          at least one kind of graph-invariants '+#13+
  '           should be involved in the modelling');
  halt;
   end; // EC0, EC1, ... EC3 are absent


writeln(r);

// hybrid indices

writeln(r);

writeln(r,
'Trshd:',
'Nact :',
'Probe:',
'  ns :',
'         rs2:',
'       ss :',
'    fs :',
'  nc :',
'         rc2:',
'       sc :',
'    fc :',
'  nt :',
'         rt2:',
'       st :',
'    ft :',
'    Rm2');

writeln(a,
'Trshd:',
'Nact :',
//'Probe:',

'  ns :',
'         rs2:',
'       ss :',
'    fs :',

'  nc :',
'         rc2:',
'       sc :',
'    fc :',

'  nt :',
'         rt2:',
'       st :',
'    ft :',
'      CCC   :',
'      Rm2av :',
'      IIC   :',
' W% :',
'N111:',
'N110:',
'N101:',
'N100:',
' SplitDefect:',
'NormSpltDef'
);

// if limn0=limne then begin dir:='model/'; probe:=1 end else dir:='search/';

//CharmName:='#Charm.txt';
//Assign(Charm,CharMname);
//Rewrite(Charm);

(*

writeln(Charm,
'  Threshold :',
'   Rtrn     :',
'   Rclb     :',
'   Rtst     :',
' ATRN+      :',
' ACLB+      :',
' ATST+      :',
' ATRN-      :',
' ACLB-      :',
' ATST-      :'
);

*)
//showmessage('#3. app[8,8]='+IntToStr(app[8,8]));

for limni:=limn0 to limne   do        // The threshold...
begin

if dir='search/'
then
begin
   if not onlyFirst then
   form1.Label24.Caption:=
   'Threshold...........'+inttostr(limni)+' to '+inttostr(limne)
   else
   begin
   form1.Label24.Caption:=
   'Threshold...........'+inttostr(limni)+' to '+inttostr(limni);
   form1.Edit23.Text:=IntToStr(limni);
   end
end
else
form1.Label24.Caption:=
'Selected threshold is '+inttostr(limni);


art:=0.0;
ast:=0.0;
aft:=0.0;
arc:=0.0;
asc:=0.0;
afc:=0.0;
are:=0.0;
ase:=0.0;
afe:=0.0;
Rm2av:=0.0;
// ini average



for probe:=1     to nprobes do       // The probe
begin

Restart:

loadSMILES('#TotalSet'+Chr(39)+'.txt'); //showmessage('LoadSMILES'); April9,2024

Total_best_TST_r:=0.0;  best_r2_TST:=0.0;
Total_best_TRN_r:=0.0;  best_r2_TRN:=0.0;

Total_best_TST_s:=10000.0;  best_s_TST:=10000.0;
Total_best_TRN_s:=10000.0;  best_S_TRN:=10000.0;

if dir='search/'
then
form1.label13.caption:=
'Probe.................'+inttostr(probe)+' to '+inttostr(nprobes)
else
form1.label13.caption:=
'   ';


sms:=form1.edit1.text;

op:=dir+'opter';
dc:=dir+'d' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // demo dcw calculation
wp:=dir+'w' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // Correlation weights
md:=dir+'m' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // model PA=C0+C1*DCW

ec:=dir+'e' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // evolution of corfrelations
                                                             // TRN CLB TST
id:=dir+'i' + intToStr(limni)+'-'+ inttostr(probe)+'.txt';   // idealization

s:=form1.edit50.Text;
modeldoc:='model/'+ s + intToStr(limni)+'-'+ inttostr(probe)+'.txt';
form1.Edit7.Text:=modeldoc;

//x2:=form1.Edit2.Text;
//x6:=form1.Edit6.Text;
//x7:=form1.Edit7.Text;

//form1.Edit10.Text:=IntToStr(limni);

//form1.Edit2.Text:=op;
//form1.Edit6.Text:=dc;
//form1.Edit7.Text:=md;

if not Model_is_loaded then iniCWs:=True
                       else iniCWs:=False;



opt0(sms,op,wp);



// showmessage('opto is OK');

If form1.CheckBox14.Checked then
begin
assign(rrr,ec);rewrite(rrr);
write  (rrr,'The evolution of correlations. The R is correlation coefficient; s is standard error');
writeln(rrr,
' W% = ',workperc,
' N111 = ',Form1.edit13.text,
' N110 = ',Form1.edit12.text,
' N101 = ',Form1.edit8.text,
' N100 = ',Form1.edit32.text,
' Nall = ',Form1.edit33.text,
' Split-Defect = ',Form1.edit35.text
);
//write  (rrr,' No.:R2-sub :R2-clb :R2-tst :R2-vld : s-sub   : s-clb   : s-tst   : s-vld   ');
write  (rrr,' No.:R2-A   :R2-P   :R2-C   :R2-V   : s-A     : s-P     : s-C     : s-V     ');

//writeln(rrr,':IIC-sub:IIC-clb:IIC-tst:IIC-vld:  CCI-sub:  CCI-clb:  CCI-tst:  CCI-vld');
writeln(rrr,':IIC-A  :IIC-P  :IIC-C  :IIC-V  :  CCI-A  :  CCI-P  :  CCI-C  :  CCI-V  ');

closefile(rrr);
end;

optimiz(op,ec);

if best_r2_TRN > total_best_TRN_r then
begin
total_best_TRN_r:=best_r2_TRN;
total_best_Probe_TRN_r:=probe;
total_best_Threshold_TRN_r:=limni;
total_best_Nepoch_TRN_r:=best_it_TRN_r;
end;

if best_r2_TST > total_best_TST_r then
begin
total_best_TST_r:=best_r2_TST;
total_best_Probe_TST_r:=probe;
total_best_Threshold_TST_r:=limni;
total_best_Nepoch_TST_r:=best_it_TST_r;
end;

if best_s_TRN < total_best_TRN_s then
begin
total_best_TRN_s:=best_s_TRN;
total_best_Probe_TRN_s:=probe;
total_best_Threshold_TRN_s:=limni;
total_best_Nepoch_TRN_s:=best_it_TRN_s;
end;

if best_s_TST < total_best_TST_s then
begin
total_best_TST_s:=best_s_TST;
total_best_Probe_TST_s:=probe;
total_best_Threshold_TST_s:=limni;
total_best_Nepoch_TST_s:=best_it_TST_s;
end;

R2_TRN_BEST[probe,limni]:=best_r2_TRN;
NEPOCH_BEST_TRN_r[probe,limni]:=best_it_TRN_r;

R2_TST_BEST[probe,limni]:=best_r2_TST;
NEPOCH_BEST_TST_r[probe,limni]:=best_it_TST_r;

S_TRN_BEST[probe,limni]:=best_s_TRN;
NEPOCH_BEST_TRN_s[probe,limni]:=best_it_TRN_s;

S_TST_BEST[probe,limni]:=best_s_TST;
NEPOCH_BEST_TST_s[probe,limni]:=best_it_TST_s;


IniCWs:=False;

saveOptimizMatrix(op,wp);


R2A:=sqr( kfkr(train,DCW,PA,types,nf) );
R2P:=sqr( kfkr(calib,DCW,PA,types,nf) );
R2C:=sqr( kfkr(test ,DCW,PA,types,nf) );
R2V:=sqr( kfkr(valid,DCW,PA,types,nf) );




if form1.CheckBox15.checked then demoDCW(dc);
MDL(md,'y');
MDL(md,'n');




dodcw;

idealization; // April9,2024
savesplit;


if R2C>R2Cmax then
     begin
     copyR2C:=R2C;
     R2Cmax:=R2C;
     bestprobe:=probe;
     savesplitLV;
     SAS:=TRUE;
     ActionOfButton28;
     SAS:=False;
     // gggg
     end; // r2c > r2cmax



//save_training(probe);

ActionOfButton28;

writeln(FYI, probe:5,':',
strToFloat(form1.edit36.text):10:0,':',
strToFloat(form1.edit13.text):10:0,':',
strToFloat(form1.edit12.text):10:0,':',
strToFloat(form1.edit8.text):10:0,':',
strToFloat(form1.edit32.text):10:0,':',
strToFloat(form1.edit33.text):10:0,':',
strToFloat(form1.edit35.text):10:3,':',
//strToFloat(form1.edit2.text):10:3, ':',
// January26,2024
RGindex(Test,dcw,PA):10:3,':',
R2A:10:4,':',
R2P:10:4,':',
R2C:10:4,':',
R2V:10:4,':',
R2Cmax:10:4,':',
bestprobe:5);

savemethod;

form1.Edit2.Text:=x2;
form1.Edit6.Text:=x6;
form1.Edit7.Text:=x7;

// showmessage('next operation...');

rt:=sqr(kfkr(Train,DCW,PA,types,nt));
rc:=sqr(kfkr(Calib,DCW,PA,types,nc));
re:=sqr(kfkr(Test ,DCW,PA,types,ne));


rt05:=sqrt(rt);
rc05:=sqrt(rc);
re05:=sqrt(re);

ft:=Fischer_PA_c0_c1_DCW(rt05,nt);
fc:=Fischer_PA_c0_c1_DCW(rc05,nc);
fe:=Fischer_PA_c0_c1_DCW(re05,ne);

c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1 );
//c0c1(Test ,DCW,PA,c00,c11,dc00,dc11);

st:=see(Train,c0,c1);
sc:=see(Calib,c0,c1);
se:=see(Test ,c0,c1);


writeln(r,
limNI:5,':',
NactSFk:5,':',
Probe:5,':',

nt:5,':',
rt:FR1:FR2,':',
st:FS1:FS2,':',
ft:7:0,':',

nc:5,':',
rc:FR1:FR2,':',
sc:FS1:FS2,':',
fc:7:0,':',

ne:5,':',
re:FR1:FR2,':',
se:FS1:FS2,':',
fe:7:0,':',
Rm2:FR1:FR2

);

art:=art + rt;
ast:=ast + st;
aft:=aft + ft;

arc:=arc + rc;
asc:=asc + sc;
afc:=afc + fc;

are:=are + re;
ase:=ase + se;
afe:=afe + fe;

rm2av:=rm2av + rm2;

// MDL(md,'n');


end; // probe

art:=art/nprobes;
ast:=ast/nprobes;
aft:=aft/nprobes;

arc:=arc/nprobes;
asc:=asc/nprobes;
afc:=afc/nprobes;

are:=are/nprobes;
ase:=ase/nprobes;
afe:=afe/nprobes;

rm2av:=rm2av/nprobes;

defect:= StrToFloat(form1.Edit35.text);
Nact:=NactSFk;

(*
showmessage
(
' Defect='+FloatToStrF(defect,FFfixed,9,4)+
' Nact ='+FloatToStrF(Nact,FFfixed,9,0)+
' T='+IntToStr(limni)
);
*)

//NormSpltDef:=( ( defect*limni)/Nact )* xiny(limni,0.33333333);
//NormSpltDef:= ( defect*xiny(limni,1.3333333) / Nact );

//NormSpltDef:= ( defect*xiny(limni,solomon) / Nact );

form1.Edit2.Text:=FloatToStrF(NormSpltDef,FFfixed,9,4);

writeln(a,
limNI:5,':',
NactSFk:5,':',
//'     :',
nt:5,':',
art:FR1:FR2,':',
ast:FS1:FS2,':',
aft:7:0,':',

nc:5,':',
arc:FR1:FR2,':',
asc:FS1:FS2,':',
afc:7:0,':',

ne:5,':',
are:FR1:FR2,':',
ase:FS1:FS2,':',
afe:7:0,':',
ccc(calib,dcw,pa,types,nccc):FR1:FR2,':',
rm2av:FR1:FR2,':',
IIC_autonom(calib,c0,c1,dcw,pa,types):FR1:FR2,':',
strToInt(form1.edit36.text):4,':',
strToInt(form1.edit13.text):4,':',
strToInt(form1.edit12.text):4,':',
strToInt(form1.edit8.text) :4,':',
strToInt(form1.edit32.text):4,':',
StrToFloat(form1.Edit35.text):12:5,':',
NormSpltDef:11:5
);

writeln(r,
limNI:5,':',
'     :',
'     :',

'     :',
art:FR1:FR2,':',
ast:FS1:FS2,':',
aft:7:0,':',

'     :',
arc:FR1:FR2,':',
asc:FS1:FS2,':',
afc:7:0,':',
'     :',
are:FR1:FR2,':',
ase:FS1:FS2,':',
afe:7:0,':',
Rm2av:FR1:FR2
);

if dir='search/' then SaveProbeStatOrder(limNI,limni);

if onlyFirsT then goto onlys1;


end; // limNI

onlys1:

series:='n';

closefile(r);
closefile(a);
// closefile(Charm);

assignfile(r,'search/#BestMDL.txt');
rewrite(r);

writeln(r,'Data from ',form1.edit1.text);
writeln(r,'Representation of molecular structure by ');
// if form1.checkBox32.Checked

begin
if form1.checkBox30.Checked then writeln(r,'* Hydrogen suppresed graph');
if form1.checkBox29.Checked then writeln(r,'* Hydrogen filled graph');
if form1.checkBox31.Checked then writeln(r,'* Graph of atomic orbitals');
end;

if form1.checkBox21.Checked then
writeln(r,'* SMILES');
writeln(r);

Writeln(r,'Correlation coefficients for the TRAINING SET');

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+R2_TRN_BEST[probe,limni];
write(r,R2_TRN_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( R2_TRN_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);

writeln(r,sum1:10:4,':',sum2:10:4 );
end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the TRAINING SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TRN_r[probe,limni];
write(r,NEPOCH_BEST_TRN_r[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TRN_r[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

Writeln(r);
//////////////////////////////////////// TRAIN R N*

Writeln(r,'Correlation coefficients for the Calibration SET');

maxRtst:=-10.0;

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+R2_TST_BEST[probe,limni];
write(r,R2_TST_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;

if sum1>maxRtst then
begin
maxRtst:=sum1;
bestT_R2:=limni;
end; // sum1 > maxRtst

sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( R2_TST_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);

write(r,sum1:10:4,':',sum2:10:4 );

//write(r,splitdefect[limni]:9:5);

writeln(r);

end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the Calibration SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TST_r[probe,limni];
write(r,NEPOCH_BEST_TST_r[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;

if limni=BestT_R2 then BestN_R2:=sum1;

sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TST_r[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

Writeln(r);
//////////////////////////////////////// TEST R N*

writeln(r);
Writeln(r,'Preferable threshold T*=',BestT_R2,'  Preferable average number of epochs   N*=',BestN_R2:5:1,'   Average R2 for calibration set =',maxRtst:9:4);
writeln(r);


Writeln(r,'Root-mean-square error for the TRAINING SET');

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+S_TRN_BEST[probe,limni];
write(r,S_TRN_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( S_TRN_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);

writeln(r,sum1:10:4,':',sum2:10:4 );
end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the TRAINING SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TRN_s[probe,limni];
write(r,NEPOCH_BEST_TRN_s[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;
sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TRN_s[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

Writeln(r);
//////////////////////////////////////// TRAIN S N*

MinRMSE:=100000000000.0;

Writeln(r,'Root-mean-square error for the calibration SET');

write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1+S_TST_BEST[probe,limni];
write(r,S_TST_BEST[probe,limni]:8:4,':');
end; // probe
sum1:=sum1/nprobes;

if sum1<MinRMSE then
begin
MinRMSE:=sum1;
bestT_RMSE:=limni;
end; // sum1 > maxRtst


sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( S_TST_BEST[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);



writeln(r,sum1:10:4,':',sum2:10:4 );
end; // threshold limni

Writeln(r);
Writeln(r,'The preferable number of epochs of the Monte Carlo optimization for the calibration SET');
write(r,' Threshold:');
for probe:=1 to nprobes do write(r,'Probe',probe:3,':');
writeln(r,' Average  :Dispersion');

for limni:=limn0 to limne do
begin
write(r,limni:10,':');

sum1:=0.0;
for probe:=1 to nprobes do
begin
sum1:=sum1 + NEPOCH_BEST_TST_s[probe,limni];
write(r,NEPOCH_BEST_TST_s[probe,limni]:8:0,':');
end; // probe
sum1:=sum1/nprobes;

if limni=BestT_RMSE then BestN_RMSE:=sum1;


sum2:=0.0;
for probe:=1 to nprobes do
begin
sum2:=sum2+sqr( NEPOCH_BEST_TST_s[probe,limni] - sum1);
end; // probe
sum2:=sqrt(sum2/nprobes);
writeln(r,sum1:10:2,':',sum2:10:2 );

end; // threshold limni

//////////////////////////////////////// TEST S N*

writeln(r);
Writeln(r,'Preferable threshold T*=',BestT_RMSE,'  Preferable average number of epochs   N*=',BestN_RMSE:5:1,'   Average RMSE for calibration set =',MinRMSE:9:4);
writeln(r);

writeln(r,'IMPORTANT:');
writeln(r,'Ideal result if the preferable threshold is the same for correlation');
writeln(r,'coefficient of the calibration set and for root-mean-square error of the calibration set.');
writeln(r,'If they are different, most probably, the threshold preferable according');
writeln(r,'to correlation coefficient of the calibration set is the indicator of the model');
writeln(r,'with higher predictive potential.');

closefile(r);

repeat
      defineRecFile(delme);
      if delme<>'No' then deletefile(delme);
until delme='No';


RecommFileName:=
'#Recommended T'
+IntToStr(BestT_R2)
+' and N'
+FloatToStrF(BestN_R2,FFfixed,5,0)
+'.txt';

assign(r,RecommFileName);
rewrite(r);
Writeln(r,'The search for the best correlation coefficient (R2) for the calibration set:');
writeln(r,'Preferable threshold T*=',BestT_R2,'  Preferable average number of epochs   N*=',BestN_R2:5:1,  '   Average R2   for calibration set =',maxRtst:9:4);
//Writeln(r,'Preferable threshold T*=',BestT_RMSE,'  Preferable average number of epochs   N*=',BestN_RMSE:5:1,'   Average RMSE for calibration set =',MinRMSE:9:4);
//writeln(r,'### If preferable thresholds (T*) for R2 and for RMSE are different, then method is not reliable.');
closefile(r);

deletefile(dir+'opter');

//form1.Button10.Visible:=True;

//form1.Button28.visible:=true;
//form1.Button29.visible:=true;
//form1.Edit50.visible:=true;

// form1.Caption:='CORAL: You must restart program for other actions';

close(FYI);

end;     // auto2



procedure ActionOfButton10;
begin
Show_TPTNFPFN:=True;
permession_to_work;

form1.Caption:='CORAL: Building up preferable model';

SwitchShowCAS('0');

loadmethod;
probe:=1;
step1;
step2;

end; // actions of button 10

procedure ActionOfButton11;
begin

SAS:=False;

SwitchShowCAS('0');

form1.Edit22.text:=form1.Edit39.Text;
form1.Edit23.text:=form1.Edit39.Text;
form1.Edit24.text:='1';

form1.Button14.Visible:=false;
form1.Button16.Visible:=false;
form1.Button17.Visible:=false;
form1.Edit19.Visible:=false;

form1.Label38.Visible:=false;
form1.Label39.Visible:=false;
form1.Label40.Visible:=false;
form1.Label41.Visible:=false;

form1.Edit44.Visible:=false;  form1.Button33.Visible:=False;
form1.Edit45.Visible:=false;
form1.Edit46.Visible:=false;
form1.Edit47.Visible:=false;
form1.Edit48.Visible:=false;
form1.Edit49.Visible:=false;
form1.Edit50.Visible:=false;

form1.Button12.Visible:=false;
form1.Button27.Visible:=false;
form1.Button28.Visible:=false;
form1.Button29.Visible:=false;

auto;

form1.Button1.Enabled:=False;
form1.Button7.Enabled:=False;
form1.Button9.Enabled:=False;
form1.Button73.Enabled:=False;

form1.Label38.Visible:=true;
//form1.Label41.Visible:=true;
form1.Edit44.Visible:=True;
form1.Button33.Visible:=True;
form1.Edit47.Visible:=True;
form1.Edit48.Visible:=True;
form1.Edit49.Visible:=True;

//form1.Button10.Visible:=true;

form1.Button12.Visible:=true;
form1.Button27.Visible:=true;

form1.Button28.Visible:=true;
form1.Button29.Visible:=false;      //      Invisivble LOAD SYSTEM button
form1.Edit50.visible:=true;

form1.button28.Visible:=True;

// file demo DCW calculation here

form1.Label39.Caption:='DCW('+form1.edit39.text+','+IntToStr(Nit)+')=';

SwitchShowCAS('1');

Form1.Caption:='CORAL: you should save model now';

Form1.Label16.visible:=False; 

end; // Action of Button 11

procedure TForm1.Button10Click(Sender: TObject);
begin
form1.Button74.Visible:=False;
form1.Edit42.Visible:=False;
form1.Edit54.Visible:=False; // October15,2024 perentage of shifting for
                             // Las Vegas algorithm
ActionOfButton10;
if model_is_loaded then ActionOfButton11;
end;

procedure TForm1.Button8Click(Sender: TObject);
begin

form1.Button7.Visible:=False;
form1.Button9.visible:=False;
form1.Button73.visible:=False;
form1.Button8.Enabled:=False;
form1.Button11.Enabled:=False;

ActionOfButton10;
ActionOfButton11;
end; // Oct27 2017

procedure version5;
var s:string; x:integer;
    k:integer;
    i,o:text;
begin
//assignfile(sym,'sym.txt'); rewrite(sym);
//Form1.button1.Visible:=False;

R2Cmax:=0.0;
Bestprobe:=0;

Show_TPTNFPFN:=True;
onlyFirsT:=False;
                
if form1.Edit22.Text=form1.Edit23.Text then
begin
x:=StrToInt(form1.Edit23.Text);
inc(x);
form1.Edit23.Text:=IntToStr(x);
onlyFirsT:=True;
end;

permession_to_work;

//showmessage('#1. app[8,8]='+IntToStr(app[8,8]));

form1.Caption:='CORAL: Search preferable T* and N*';
userinformed:=False;

SwitchShowCAS('0');

if form1.Edit1.text='***' then
begin
showmessage('Method should be loaded before start of calculation');
exit;
end; // Method is not loaded

//form1.Button16.Enabled:=false;
form1.Button17.Enabled:=false;
form1.Button15.Enabled:=false; // scheme
form1.Button19.Enabled:=false; // Lim N/S must be not available after START...



// form1.Edit19.Visible:=false;

form1.Label9.visible:=false;
form1.Label10.Visible:=false;
form1.Label34.visible:=false;
form1.Label38.Visible:=false;
form1.Label39.visible:=false;
form1.Label40.Visible:=false;
form1.Label41.visible:=false;

form1.Edit4.Visible:=false;
form1.Edit5.Visible:=false;

form1.edit4.Text:='0';
form1.edit5.Text:='1';

form1.Edit39.Visible:=false;
form1.Edit44.Visible:=false;
form1.Button33.Visible:=False;
form1.Edit45.Visible:=false;
form1.Edit46.Visible:=false;
form1.Edit47.Visible:=false;
form1.Edit48.Visible:=false;
form1.Edit49.Visible:=false;

form1.Button10.Visible:=false;
form1.Button11.Visible:=false;
form1.Button12.Visible:=false;
form1.Button27.Visible:=false;

if StrToInt( form1.edit22.text)> StrToInt(  form1.edit23.text) then
begin
showmessage('Definition of range for threshold is wrong. Program will be halted');
halt;
end; // Threshold: Start>Finish

if StrToInt( form1.edit24.text)> MaxProbes then
begin
showmessage('Maximum of probes of Monte Carlo optimization is '+inttostr(maxprobes));
form1.Edit24.Text:=inttostr(maxprobes);
form1.Edit42.Text:=inttostr(maxprobes);
end; // Threshold: Start>Finish

//showmessage('#2. app[8,8]='+IntToStr(app[8,8]));

auto2; // April3,2024

//Form1.Caption:=' CORAL ';

if version = 3 then
showmessage
('In order to select preferebale threshold (T*), please see files'+#13+
 ' - search/#a.txt (average statistical characteristics)'+#13+
 ' - search/#r.txt (all statistical characteristics);'+#13+
 'In order to select preferable number of epochs (N*), please see'+#13+
 ' - search/#BestMDL.txt'
 )
else
begin
// May28,2024
//showmessage( ''+#13+#13+  'Please use #TotalSetLV.txt for building up the model' +#13+  '');
//s:='';   June4,2024
//for k:=1 to LV do s:=s+LVlist[k]+#13;
//showmessage(s);

k:=LVbest-1; if k<1 then k:=1;
//showmessage('LVbest='+IntToStr(k));
LVBest:=k;

//showmessage('File is '+LVList[LVbest]);

assign(i,LVList[LVbest]); reset(i);
assign(o,'#TotalSetLV.txt'); rewrite(o);

repeat
readln(i,s); writeln(o,s);
until eof(i);

close(i);
close(o);

showmessage('#TotalSetLV.txt contains the split recommended by Las Vegas algorithm');
deleteLV('model/');

deleteFile('!FYI.txt');

end; // analysis of Las Vegas algorithm reslts May28,2024

SwitchShowCAS('1');
//closefile(sym);
halt;

end; // version5


procedure version3;
var s:string; x:integer;
begin

Form1.button1.Visible:=False;

Show_TPTNFPFN:=True;
onlyFirsT:=False;

if form1.Edit22.Text=form1.Edit23.Text then
begin
x:=StrToInt(form1.Edit23.Text);
inc(x);
form1.Edit23.Text:=IntToStr(x);
onlyFirsT:=True;
end;

permession_to_work;

form1.Caption:='CORAL: Search preferable T* and N*';
userinformed:=False;

SwitchShowCAS('0');

if form1.Edit1.text='***' then
begin
showmessage('Method should be loaded before start of calculation');
exit;
end; // Method is not loaded

form1.Button16.Enabled:=false;
form1.Button17.Enabled:=false;
form1.Button15.Enabled:=false; // scheme
form1.Button19.Enabled:=false; // Lim N/S must be not available after START...



// form1.Edit19.Visible:=false;

form1.Label9.visible:=false;
form1.Label10.Visible:=false;
form1.Label34.visible:=false;
form1.Label38.Visible:=false;
form1.Label39.visible:=false;
form1.Label40.Visible:=false;
form1.Label41.visible:=false;

form1.Edit4.Visible:=false;
form1.Edit5.Visible:=false;

form1.edit4.Text:='0';
form1.edit5.Text:='1';

form1.Edit39.Visible:=false;
form1.Edit44.Visible:=false; form1.Button33.Visible:=False;
form1.Edit45.Visible:=false;
form1.Edit46.Visible:=false;
form1.Edit47.Visible:=false;
form1.Edit48.Visible:=false;
form1.Edit49.Visible:=false;

form1.Button10.Visible:=false;
form1.Button11.Visible:=false;
form1.Button12.Visible:=false;
form1.Button27.Visible:=false;

if StrToInt( form1.edit22.text)> StrToInt(  form1.edit23.text) then
begin
showmessage('Definition of range for threshold is wrong. Program will be halted');
halt;
end; // Threshold: Start>Finish

if StrToInt( form1.edit24.text)> MaxProbes then
begin
showmessage('Maximum of probes of Monte Carlo optimization is '+inttostr(maxprobes));
form1.Edit24.Text:=inttostr(maxprobes);
end; // Threshold: Start>Finish

auto;

//Form1.Caption:=' CORAL ';

showmessage
('In order to select preferebale threshold (T*), please see files'+#13+
 ' - search/#a.txt (average statistical characteristics)'+#13+
 ' - search/#r.txt (all statistical characteristics);'+#13+
 'In order to select preferable number of epochs (N*), please see'+#13+
 ' - search/#BestMDL.txt'
 );

SwitchShowCAS('1');

halt;

end; // version3


procedure TForm1.Button14Click(Sender: TObject);
var s:string; x:integer;
begin
phase := 1;

form1.button74.Enabled:=False;
if version=5 then
             begin
             show_optimiz:=True;
             form1.button14.Caption:=' Las Vegas Calculations in process';
             form1.Edit24.Text:=form1.Edit42.Text;
             version5;
//             showmessage('Take out list of files names from Model');
             end
             else version3;

end; // Search for preferable Threshold


procedure TForm1.Button16Click(Sender: TObject);
begin
savemethod;
end;

procedure TForm1.Button17Click(Sender: TObject);
begin

show_optimiz := not show_optimiz;

if show_optimiz then
                   begin
                     form1.Button21.Caption:='Show optimization';
                     form1.Edit14.Text:='...';
                     form1.Edit15.Text:='...';
                     form1.Edit16.Text:='...';
                     end
                else form1.Button21.Caption:='Hide';



Phase:=2;

version:=3; // no Las Vegas April9,2024


form1.Button73.Visible:=True;
form1.Button10.Visible:=True;

dotsize:=1;
assignfile(sym,Report);rewrite(sym);

Form1.Button29.Visible:=True;
print_VLD:=False;

//setscreen;

form1.Button1.Enabled:=False;

Model_is_loaded:=False;
show_TPTNFPFN:=True;
loadmethod;
form1.Caption:='CORAL: select Phase (1 or 2); or change and save method; or import current model';
end; // Button17click


procedure TForm1.Button19Click(Sender: TObject);
begin

limSlimN;

end; // ButtonClick19

procedure do_Endpoint_for_external_list;   // April 1, 2020

Var
      i,o:text;
      iname, oname:string;
      cas,
      sms:string;
      SMSdef:real;
begin
iname:=form1.Edit51.Text;
oname:=form1.Edit52.Text;

assign(i,iname);

assignfile(i,iname);
{$I-}
reset(i);
{$I+}
if IOResult <> 0 then
begin
ShowMessage('File "'+iname+'" not found. Please prepare the file');
exit;
end; // iname is not found

assign(o,oname); rewrite(o);

//writeln(o,' Average Defect SMILES (ADS)) = ', floatToStrF( aveDefectSMILES, FFfixed, 12,4));
//writeln(o,' SMILES that has Defect less than ',floatToStrF(2*aveDefectSMILES,FFfixed,12,4),' falls in Domain of applicability');

repeat
readln(i,SMS);
form1.Edit44.Text:=sms;
externalSMILES;


// October 12, 2020
//SMS:=form1.edit46.text;

write(o,SMS,'  :  ',form1.edit46.text,':');


//SMSdef:=SMILES_defect(SMS,CAS,local_SF_list);
//write(o,SMSdef:12:4,':');

//if SMSdef>2*AveDefectSMILES then write(o,' Outlier    :')
//                            else write(o,' Non-outlier:');
writeln(o);

until eof(i);

close(o);
close(i);

showmessage('Please see file '+form1.Edit52.Text);

end; // do_Endpoint_for_extenal_list;



procedure TForm1.Button20Click(Sender: TObject);

begin

do_Endpoint_for_external_list;



//Save_all_CWs:=not Save_all_CWs;
//if save_all_CWs then form1.Button20.Caption:='Save ALL CWs'
//                else form1.Button20.Caption:='Save ACT CWs'

end; // Button20click

procedure TForm1.Button15Click(Sender: TObject);
label outoff;
begin

form3.show;

(*
if scheme='+' then
begin
scheme:='*';
goto outoff;
end;
if scheme='*' then
begin
scheme:='+';
end;

outoff:
if scheme='+' then form1.button15.Caption:='Adding'
              else form1.button15.Caption:='Multiply';

//scheme:='*';         form1.label20.caption:=scheme;
*)
end; // button click 5

procedure TForm1.Button18Click(Sender: TObject);
begin
scheme:='+';         form1.label20.caption:=scheme;
end;

function NumberOfSF(var name:CWsName):integer;
var rez:integer;
    glb:integer;
begin
rez:=0;
for glb:=1 to N_glb do
if CWsNameSame(name,Global_SF_list[glb]) then rez:=glb;
NumberOfSF:=rez;
end; // NumberOfSF

procedure TForm1.Button21Click(Sender: TObject);
begin

// May4,2023 show process of the Monte Carlo optimization or not

show_optimiz := not show_optimiz;

if show_optimiz then
                   begin
                     form1.Button21.Caption:='Show optimization';
                     form1.Edit14.Text:='...';
                     form1.Edit15.Text:='...';
                     form1.Edit16.Text:='...';
                     end
                else form1.Button21.Caption:='Hide';
end;

procedure TForm1.Button23Click(Sender: TObject);
begin
authomat:= not authomat;
if authomat then button23.Caption:='Selfcontrol'
            else button23.Caption:='Interactive'
end;


procedure TForm1.Button11Click(Sender: TObject);     // Building of model
begin
form1.Button10.Enabled:=False;
form1.Button11.Enabled:=False;
form1.Button15.Enabled:=False;

ActionOfButton11;

end;

procedure TForm1.Button12Click(Sender: TObject);
begin
ExternalSMILES;
end;

Procedure ExternalSMILES_from_File
          (var f:text;
           memoType,
           types:char;
           var CAS:string;
           var expr,ep:real;
           id:integer;
           var DCWdefect:real;
           var outliers:integer
           );
var k,j,No:integer;
    SMILES,
    sms,
    fname,
    msg,
    rez,
    Chana:string;
    NatSFk,
    c0,c1,
//    DCWdefect,
    dcw:real;
    x:text;
begin
Chana:='noChana';

fname:=dir+form1.Edit47.Text;

SMILES:=form1.Edit44.Text+BCE;
sms:=SMILES;

//write(f,id:5,' ',types[id],':',CAS:15,':');
write(f,Memotype,':',CAS:15,':');

StringStandard(sms,msg,'?'); write(f,msg);

write(f,':');

probe:=1;

SMS_in_SF(SMILES,Chana,Local_SF_list,n_loc);

nuc[id,0]:=n_loc;
for j:=1 to n_loc do
begin
nuc[id,j]:=CWnumber(local_SF_list[j],n_glb);
end; // j


DCW:=0.0;

DCWdefect:=0.0;

for k:=1 to n_loc do
begin

NatSFk:= NaturalCW(LOcal_SF_list[k],No);

DCW:=DCW+NatSFk;

DCWdefect:=DCWdefect + CWdefect[No];      // 

end; // k

//  February9,2023
//  The problem with calculation from file

// if cas='103-50-4' then showmessage(FloatToStrF(dcw,FFfixed,9,4));

form1.Label39.Visible:=true;
form1.Label40.Visible:=true;
form1.Edit45.Visible:=true;
form1.Edit46.Visible:=true;

form1.Edit45.Text:=FloatToStrF(DCW,FFfixed,12,ffd); // May11,2023 ffd!

c0:=StrToFloat(form1.edit4.text);
c1:=StrToFloat(form1.edit5.text);

EP:=c0+c1*dcw;

form1.Edit46.Text:=FloatToStrF(EP,FFfixed,12,ffd);  // May11,2023 ffd!

Write(f,DCW:12:ffd,':',ExPr:12:ffp,':',EP:12:ffp,':');
Write(f,ExPr-EP:12:ffp,':');

//Write(f,DCW:12:ffd,':',ExPr:12:ffp,':');

if classification then
begin
if (ExPr>middle01) and (EP>=middle01) then begin rez:='       TP   :'; inc(GTP) end;
if (ExPr>middle01) and (EP<=middle01) then begin rez:='       FN   :'; inc(GFP) end;
if (ExPr<middle01) and (EP<=middle01) then begin rez:='       TN   :'; inc(GTN) end;
if (ExPr<middle01) and (EP>=middle01) then begin rez:='       FP   :'; inc(GFN) end;

end;

write(f,rez);


//Write(f,DCWdefect:12:4,':',smiles_defect(SMILES,cas,Local_SF_list):12:4);
// October 12, 2020
Write(f,smiles_defect(SMILES,cas,Local_SF_list):12:4,':');


if DCWdefect<AveDefectSMILES+AveDefectSMILES then
                                              begin
                                              write(f,'    YES   ');
                                              // Oct7,2022 !Domain.txt
                                              writeln(domain,
                                              types,cas,' ',
                                              form1.edit44.text,expr:9:3);

                                              end
                                             else
                                             begin
                                              write(f,'          No');
                                              inc(outliers);
                                              writeln(domaino,
                                              types,cas,' ',
                                              form1.edit44.text,expr:9:3);

                                             end;
Writeln(f);

end;  // ExternalSMILES_from_file()

function maxlengthininput:integer;
var
    s,
    fli:string;
    max,
    ls,
    n,
    j,
    k:integer;
    f:text;
    c:char;
begin

fli:= form1.Edit48.Text;

max:=0;
assign(f,fli);
reset(f);

readln(f,n);

for k:=1 to n do
begin
readln(f,s);
ls:= length(s);

for j:=1 to ls do
begin
c:=s[j];
if c=BAR then
begin
c:=reBAR;
DotInSMILES:=
'Some SMILES are containing dot (i.e. "."); Please use "'+c+'" instead of symbol "."!';
end;
end;


if ls>max then max:=ls;
end;

maxlengthininput:=max;
closefile(f);
end; // max length in input

procedure do_good_file(inputname,outputname:string);
var part1:array[1..MaxSMS] of string; // February8,2023
    part2:array[1..MaxSMS] of string; // December 10,2020
    part3:array[1..MaxSMS] of string;
    n1,
    n2,
    n3:integer;
    k:integer;
    o,
    i:text;
begin

assign(i,inputname); reset(i);

k:=0;
repeat k:=k+1;
readln(i,part1[k]);
until part1[k]='***';
n1:=k-1;

k:=0;
repeat k:=k+1;
readln(i,part2[k]);
until part2[k]='$$$';
n2:=k-1;

k:=0;
repeat k:=k+1;
readln(i,part3[k]);
until eof(i);
n3:=k;
close(i);

assign(o,outputname); rewrite(o);

for k:=1 to n1 do writeln(o,part1[k]);
for k:=1 to n3 do writeln(o,part3[k]);
for k:=1 to n2 do writeln(o,part2[k]);

close(o);

end; //

function VLD_NumberActive(Activity:real):integer;
Var
     rez,
     k:integer;
begin
rez:=0;
for k:=1 to nsms do
if types[k]=Valid then
begin
if abs(Pa[k]-activity)<0.0000000001 then inc(rez);
end;

VLD_NumberActive:=rez;
end; // VLD_NumberActive


procedure DCW_EndPoint_For_SMILES_from_file;
label outoff;
var
     i,o,oo,ooo:text;
     c:char;
     txt,
     msg,
     CASloc,
     SMILES,
     fli,   // file input
     flo,   // file output model
//     floo,  // SMILES file where instead of EP delta=expr-calc are printing
//     flooo, // SMILES file where instead of EP SMILES_defect are printing
     Modeldetails, // name file where data on the model
     mss,
     s:string;
     NIF,   // number in fact = nmr + nsms
     j,nmr,the_number:integer;
     Nact,
     NsmsTRN,
     NsmsTST: integer;
     defect_TRN_VLD,
     expr:real;
     nsmscopy,
     KRoyIndex:integer;
     q2_VLD,
     q2t,
     q2c,
     q2v,
     q2e,
     c0,c1, dc0,dc1, delta,
     MAE,rmse,rez1,rez2,rm2,rm2copy,kk,kkk,r2,r02,rr02:real;
     SMILES_defect:real;
     memoType:char;
     Outliers:integer; // the number of outliers according to inequality 'x<2X'
     _parol:char; // for q2(VLD) calculation March 24, 2017
     nccc:integer; // N for calcution CCC, in fact thei is a fictive value
     k:integer; // index for good file name doing... May 11, 2018
begin

valid:='*';
ModelDetails:='model/'+form1.Edit50.Text;

if not fileexists(ModelDetails) then
begin
showmessage('In order to use the model, you need preliminary to save File '+
ModelDetails);
exit;
end; // not file exists

nmr:=0;
(*
mss:=
'Please insert file "'+form1.Edit48.Text+'" in folder "model"'+#13+
'This file should be similar the following:'+#13+
'3'+#13+
'#373-02-4 C(=O)([O-])C.C(C)(=O)[O-].[Ni+2] -1.380'+#13+
'-127-82-2 S(c1ccc(O)cc1)(=O)(=O)[O-].S(c1ccc(O)cc1)(=O)(=O)[O-].[Zn+2] 1.370'+#13+
'+137-30-4 C(=S)(N(C)C)[S-].[S-]C(N(C)C)=S.[Zn+2] 1.23';

showmessage(mss);
*)


fli:= form1.Edit48.Text;
flo:='model/'+form1.Edit49.Text;
//floo:='model/RMSE'+form1.Edit49.Text;
//flooo:='model/SMSdefct'+form1.Edit49.Text;

//floo:='model/Expr-Calc.txt';
//flooo:='model/SMILESdefect.txt';

assignfile(i,fli);
{$I-}
reset(i);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+fli+' not found: Input file must be in CORAL folder.'
+#13
+#13+'It should be in format:'
+#13
+#13+'3                                       // the number of substances'
+#13+'+77-11-3 CCCCNCCC[N+] 2.33'
+#13+'-555-33-9 ClCC1CCCCC1 -1.215'
+#13+'#333-12-1 [N+][O-]C1ccccc1 1.5'
);
Halt;
end;

MaxSMILESlength2:=maxlengthininput;

readln(i,the_number);  if the_number=0 then halting('Validation set is empty');

if the_number>MaxInput then
begin
showmessage('Input File is too long, max= '+inttostr(MaxInput)+#13+
            ' Further calculations are impossible.'
 );
halt;
end; // the number > max_input

KRoyN:=the_number;

for nmr:=1 to the_number do
begin

CASloc:='';
 j:=0;
 repeat j:=j+1;
 read(i,c);
 if j=1 then c:='*';
 CASloc:=CASloc+c;
 until c=' ';

SMILES:='';
 repeat
 read(i,c);
 if c=BAR then c:=reBAR;
 SMILES:=SMILES + c;
 until c=' ';

Readln(i,expr);

PA  [nsms+nmr]:=expr;
PA01[nsms+nmr]:=expr;

if length(s)>MaxSMILESlength2 then MaxSMILESlength2:=length(s);

end; // nmr
closefile(i);

inc(MaxSMILESlength2);

assignfile(o,flo);
{$I-}
rewrite(o);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+flo+' cannot be open. Try to use other name for file');
goto outoff;
end;

if classification then
begin
GTP:=0;
GFP:=0;
GTN:=0;
GFN:=0;

end;


Writeln(o,'This file contains prediction for the invisible validation set');
writeln(o);
//if form1.CheckBox35.Checked
//then writeln(o,'Optimization based on hybrid R[TRN] and CCC[iTRN]')
//else writeln(o,'Optimization based on the traditional correlation coefficient (r2)');
//writeln(o);

Writeln(o,'Data taken from file ',Fli);
writeln(o);
Writeln(o,'The average of DefectSMILES =',AveDefectSMILES:12:5);
Writeln(o,
'Substance falls into domain of applicability if DefectSMILES < ',
AveDefectSMILES+AveDefectSMILES:12:5);
Writeln(o,'***');

txt:='SMILES ';
write(o,'Set:');
write(o,'        CAS  :');
StringStandard(txt,msg,'*');
write(o,msg);
write(o,':  DCW       ');
write(o,':  Expr      ');
write(o,':  Calc      ');
write(o,': Expr-Calc  ');

If classification then write(o,':  Class     ');
write(o,':DefectSMILES');
write(o,': Applicability ');
writeln(o);

assignfile(i,fli);
{$I-}
reset(i);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+fli+' is not found');
goto outoff;
end;

(*
assignfile(ooo,flooo);
{$I-}
rewrite(ooo);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+flooo+' cannot be open. Try to use other name for file');
goto outoff;
end;
*)

KRoyIndex:=0;

readln(i,the_number);

outliers:=0;

for nmr:=1 to the_number do
begin

NIF:=nmr + nsms;
// showmessage( IntToStr(nmr+nsms) +' Oct21,2022 ');

inc(KroyIndex);

read(i,c); memoType:=c; types[NIF]:=Valid;    // March27, 2015

CAS[NIF]:='';
 repeat
 read(i,c);
 if c<>' ' then CAS[NIF]:=CAS[NIF]+c;
 until c=' ';

// showmessage( CAS[NIF] +' Oct21,2022 ');

SMS[NIF]:='';
 repeat
 read(i,c);
 if Form1.checkbox32.Checked then
 if c='.' then
    begin
//    showmessage(CAS[NIF]+' contains dot. Please correct '+Fli);
//    halt;
    end; // c='.'
 if c=BAR then c:=reBAR;
 if c<>' ' then SMS[NIF]:=SMS[NIF]+c;
 until c=' ';

//showmessage( SMS[NIF] +' Oct21,2022 ');


Readln(i,expr); PA[NIF]:=expr; exprcalc[NIF,1]:=expr;

s:=SMS[NIF];
//types[nsms+nmr]:=CASloc[1];
//types[NIF]:=Valid;

//sms  [nsms+nmr]:=SMILES;

form1.Edit44.Text:=s;

//showmessage('SMS='+form1.edit44.Text);

ExternalSMILES_from_file(o,
                         memoType,
                         types[NIF],
                         CAS[NIF],
                         exprcalc[NIF,1],
                         exprcalc[NIF,2],
                         NIF,
                         SMILES_defect,
                         outliers
                         );

(*
write(ooo,types[NIF],cas[NIF],' ');

for j:=1 to length(sms[NIF])-1 do
 begin

 write(ooo,sms[NIF][j]);
 end; // j
*)
//writeln(ooo, SMILES_defect-AveDefectSMILES:9:5);
//writeln(ooo, SMILES_defect:9:5);

//PA[nsms+nmr]:=exprcalc[nmr,1];

Kroyx[KRoyIndex]:=exprcalc[NIF,1];
Kroyy[KroyIndex]:=exprcalc[NIF,2];


end; // nmr


//closefile(ooo);
closefile(i);

nsmscopy:=nsms;

nsms:=nsms+nmr-1;

//showmessage('PROBE ='+inttostr(probe));

doDCW;                //

//c0c1(Train,DCW,PA,c0 ,c1 ,dc0 ,dc1 );

c0:=StrToFloat(form1.edit4.text);             // April 2, 2020
c1:=StrToFloat(form1.edit5.text);

//showmessage('c0 c1 are OK');

(**
q2t:=q2(train,DCW,PA,c0,c1);
q2c:=q2(calib,DCW,PA,c0,c1);
q2v:=q2(test ,DCW,PA,c0,c1);
q2e:=q2(valid,DCW,PA,c0,c1);
showmessage('q2t q2c q2v q2e are OK');
(**)
//DoNotQ2:=False;
//q2_VLD:=q2(Valid,DCW,PA,c0,c1);

// Rm2-validation charcaterristics start     April8-2015
(*
assignfile(oo,floo);
{$I-}
rewrite(oo);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+floo+' cannot be open. Try to use other name for file');
goto outoff;
end;
*)



rmse:=0.0;
MAE:=0.0;
for nmr:=1 to the_number do
begin
NIF:=nmr + nsmscopy;
delta:=exprcalc[NIF,1]-exprcalc[NIF,2];
rmse:=rmse + sqr(delta);
MAE:=MAE   + abs(delta);


//write(oo,types[NIF],cas[NIF],' ');


//for j:=1 to length(sms[NIF])-1 do
// begin
// write(oo,sms[NIF][j]);
// end; // j

//writeln(oo, delta:9:3);


end;

//closefile(oo);


rmse:=sqrt( rmse/(the_number-1) );
MAE := MAE / the_number;


writeln(o);
writeln(o,'The number of outliers is ',outliers);
writeln(o,'$$$');

if not classification then
begin
writeln(o);
writeln(o,'Rm2(x,y) calculation for validation set from input file');
Kroy(KRoyN,kk,kkk,r2,r02,rr02,rm2,KRoyY,KRoyX);
writeln(o,'n           =',KroyN:8);
writeln(o,'r2          =',r2:10:4);
writeln(o,'r02         =',r02:10:4);
writeln(o,'rr02        =',rr02:10:4);
rez1:=(r2-r02)/r2;
rez2:=(r2-rr02)/r2;
writeln(o,'(r2-r02)/r2 =',rez1:10:4,' should be < 0.1');
writeln(o,'(r2-rr02)/r2=',rez2:10:4,' should be < 0.1');
writeln(o,'k           =',kk:10:4, ' should be 0.85 <  k < 1.15');
writeln(o,'kk          =',kkk:10:4,' should be 0.85 < kk < 1.15');
writeln(o,'Rm2(test)   =',Rm2:10:4,' should be > 0.5');
writeln(o);
end;

if not classification then
begin
rm2copy:=rm2;

Kroy(KRoyN,kk,kkk,r2,r02,rr02,rm2,KRoyX,KRoyY);


writeln(o);
writeln(o,'Rm2(y,x) calculation for validation set from input file');
writeln(o,'n           =',KroyN:8);
writeln(o,'r2          =',r2:10:4);
writeln(o,'r02         =',r02:10:4);
writeln(o,'rr02        =',rr02:10:4);
rez1:=(r2-r02)/r2;
rez2:=(r2-rr02)/r2;
writeln(o,'(r2-r02)/r2 =',rez1:10:4,' should be < 0.1');
writeln(o,'(r2-rr02)/r2=',rez2:10:4,' should be < 0.1');
writeln(o,'k           =',kk:10:4, ' should be 0.85 <  k < 1.15');
writeln(o,'kk          =',kkk:10:4,' should be 0.85 < kk < 1.15');
writeln(o,'R*m2(test)  =',Rm2:10:4,' should be > 0.5');

writeln(o);
writeln(o,'Average Rm2 =',0.5*(rm2copy+rm2):7:4,' should be larger 0.5');
writeln(o,'Delta Rm2 =',abs(rm2copy-rm2):7:4,' should be lower 0.2');
writeln(o);
writeln(o,'IIC(validation)             =',IIC_autonom(valid,c0,c1,dcw,pa,types):9:4);
writeln(o,'CII(validation)             =',CCI(valid,c0,c1,dcw,pa,types):9:4);
writeln(o,'RMSE(validation)            =',rmse:9:4);
writeln(o,'MAE(validation)             =',mae :9:4);
writeln(o,'CCC(validation)             =',ccc(valid,dcw,pa,types,nccc):9:4);
writeln(o,'Y-randomization(validation) =',Y_randomization(valid,c0,c1,dcw,pa,types):9:4);
writeln(o,'q2(validation)              =',q2          ( valid, dcw, pa, c0,c1):9:4);
writeln(o,'CCCP                        =',RGindex( valid, dcw, pa):9:4);
end;

// Rm2-validation charcaterristics end


//NsmsTRN:=number_SMILES_in_SET(train);
//NsmsTST:=number_SMILES_in_SET('*');

//showmessage('NsmsTRN='+IntToStr(NsmsTRN)+'  NsmsTST='+ IntTostr(NsmsTST) );

//for nmr:=1 to n_glb do
//begin
//Trns[nmr]:=N_SMILESs_with_SFk(Train,Global_SF_list[nmr]);
//Tsts[nmr]:=N_SMILESs_with_SFk( '*' ,Global_SF_list[nmr]);
//end; // i

//q2_VLD:=q2(Valid,DCW,PA,c0,c1);

Nact:=NactSFk;

writeln(o);

//writeln(o,'The total number of SMILES in training   (TRN) set =',NsmsTRN);
//writeln(o,'The total number of SMILES in validation (VLD) set =',NsmsTST);
writeln(o,'The number of active (not blocked) attributes      =',Nact);
writeln(o);

(*
if not classification then
begin
writeln(o,'Q2-Training set    =',q2t:9:4);
writeln(o,'Q2-Calibration set =',q2c:9:4);
writeln(o,'Q2-Test set        =',q2v:9:4);
writeln(o,'Q2-Validation set  =',q2e:9:4);
end;
*)

if classification then
begin

// September 10,2020
writeln(o,'The basis of the classification model:');
//writeln(o,'Middle01 = ',middle01:7:3);
writeln(o,'The number of active   =',VLD_NumberActive(max01) );
writeln(o,'The number of inactive =',VLD_NumberActive(min01) );
writeln(o,'%%%2');
dodcw;
for nmr:=1 to nsms do PAcalc[nmr]:=c0+c1*DCW[nmr];
show_class(o,Valid);
end; // classification

closefile(o);


form1.Caption:=Display_memory;

mss:='DCW/EndPoint calculation for data from '+fli+' is completed.'+#13+#13+
 'The numerical data is saved in '+flo+'.'+#13+#13+
 'Next picture will be graphical representation of the model for '+#13+
 'Active training set;';

if form1.RadioButton1.Checked then mss:=mss + ' Passive training set;';

mss:=mss +' Calibration set; and '+' Validation set. '+#13+#13;
mss:=mss + 'File "DOMAIN.txt" contains the Domain of applicability,i.e. data without outliers'+#13;
mss:=mss + 'which are defined according to the statistical defects calculated for SMILES '+#13;
mss:=mss + 'or quasi-SMILES applied to build up the given model; file "DOMAINO.txt" contains outliers'+#13;

if
(form1.checkbox59.Checked) or
(form1.checkbox98.Checked) or
(form1.checkbox35.Checked) or
(Form1.CheckBox132.Checked)
then
mss:=mss +#13+ 'File '+Report+' contains data on Symmetry';


modeldetails:='';
for k:=1 to length(flo)-4 do modeldetails:=modeldetails+flo[k];
modeldetails:=modeldetails+'$.txt';

do_good_file(flo,modeldetails);
deletefile(flo);

showmessage(mss);

outoff:
//halt;
end; //  DCW_EndPoint_For_SMILES_from_file qqq

procedure correct_dot_in_comma(var s:string);
var k,n:integer;
begin
n:=length(s);
for k:=1 to n do
if s[k]='.' then s[k]:=',';
end; // correct_dot_in_comma(s);

procedure correct_comma_in_dot(var s:string);
var k,n:integer;
begin
n:=length(s);
for k:=1 to n do
if s[k]=',' then s[k]:='.';
end; // correct_comma_in_dot(s);

function delta(x,y:real):real;
begin
delta:=x-y;
end; // delta

procedure saveLine(var f:text;var types:char;var cas:string;var sms:string;var pa:real);
var k:integer;
begin
write(f,types,cas,' ');
for k:=1 to length(sms)-1 do write(f,sms[k]);
writeln(f,pa:9:3);
end;

procedure delete_duplicates_in_VLD;
label nextX;
var i,o:text;
    txt,
    nameo,
    namei:string;
    r,
    start,
    finish,
    x,y,
    t,
    nVLD,
    ksms:integer;
    nsmscopy:integer;
begin

namei:=form1.Edit48.Text;
assign(i,namei);reset(i);

readln(i,nVLD);
t:=0;
start:=nsms+1;
ksms:=nsms;
repeat ksms:=ksms+1;
read_sms(i,types[ksms],cas[ksms],sms[ksms],chana[ksms],pa[ksms],ksms);
//doReBAR(sms[ksms]);
t:=t+1;
//showmessage(sms[ksms]);
until eof(i);
finish:=ksms;

for x:=start to finish do types[x]:='*';

close(i);
(*
assign(o,'!x.txt');rewrite(o);
for x:=1 to ksms do saveline(o,types[x],cas[x],sms[x],pa[x]);
close(o);

showmessage(
'start = '+IntToStr(start)
+' Finish = '+IntToStr(Finish)
+' Total = '+IntToStr(t)
+' nsms = '+IntToStr(nsms)
+' nVLD = '+IntToStr(nVLD)
);
*)

for x:=start to finish do
begin
for y:=1 to nsms do if stringsduplicates(sms[x],sms[y]) then types[x]:=Reject;
end; // x

(*
assign(o,'!!x.txt');rewrite(o);
for x:=1 to ksms do saveline(o,types[x],cas[x],sms[x],pa[x]);
close(o);
*)
//showmessage('t = '+inttoStr(t));

t:=0;
for x:=start to finish do if types[x]<>reject then t:=t+1;

if t<nVLD then
begin

   txt:='There are some SMILES (n='+IntToStr(nVLD-t)+
   ') that present simultaneously'+
   ' in VLD and TRN, iTRN, or VLD'+#13+
   'Do you want remove from VLD, '+
   'SMILES that present in TRN, iTRN, or CLB ?';
   r:=messageDlg(txt,mtConfirmation,[mbYes,mbNo],0);
   if r=mrYES then
   begin


   assign(o,'copy_'+namei);rewrite(o);
   writeln(o,nVLD);
   for x:=1 to nVLD do saveline(o,types[x],cas[x],sms[x],pa[x]);
   close(o);

   deletefile(namei);
   assign(o,namei); rewrite(o);
   writeln(o,t);
   for x:=start to finish do
   if types[x]='*' then saveline(o,types[x],cas[x],sms[x],pa[x]);
   close(o);
   end; // r=mrYES

end; // t<nVLD
end; // delete_duplicates_in_VLD


procedure TForm1.Button27Click(Sender: TObject);
var s:string;
    r:integer;
    f:textfile;
    k:integer;

begin
marker:=1; // print symmetry is not need

assignfile(domain,'DOMAIN.txt'); rewrite(domain);
assignfile(domaino,'DOMAINo.txt'); rewrite(domaino);

//form1.label27.Visible:=true;

print_vld:=True;

// dRsms;

form1.Button27.Enabled:=False;
show_TPTNFPFN:=True;
form1.Button8.Enabled:=False;

// ggg
if here_comma then
begin
//showmessage('Here comma, not dot !');
s:=form1.Edit4.Text;  correct_dot_in_comma(s); form1.Edit4.Text:=s;
s:=form1.Edit5.Text;  correct_dot_in_comma(s); form1.Edit5.Text:=s;
end
else
begin
//showmessage('Here dot, not comma !');
s:=form1.Edit4.Text;  correct_comma_in_dot(s); form1.Edit4.Text:=s;
s:=form1.Edit5.Text;  correct_comma_in_dot(s); form1.Edit5.Text:=s;
end; // here_comma



             form1.Button29.Enabled:=False;

Display_memory:=form1.Caption;

form1.Caption:=
' Please wait! You will be informed when calculations will be completed...';

//r:=messageDlg('Do you want to make sure there are not duplicates',mtConfirmation,[mbYes,mbNo],0);
//   if r=mrYES then delete_duplicates_in_VLD;

DCW_Endpoint_For_SMILES_from_file;

// February8,2023

do_vld:=true;

// dodcw;

clearplot(x10,y10);
clearplot(x20,y20);
clearplot(x30,y30);

(*
x10:= 57; y10:= 105;
x20:= 57; y20:= 220;
x30:= 57; y30:= 330;
x40:= 57; y40:= 443;
rx :=130; ry :=  60;
*)

x10:= 57; y10:= 110;
x20:= 57; y20:= 220;
x30:= 57; y30:= 330;
x40:= 57; y40:= 443;
rx :=130; ry :=  60;



form1.Edit14.Visible:=false;
form1.Edit15.Visible:=false;
form1.Edit16.Visible:=false;
form1.Edit17.Visible:=false;

form1.button30.Visible:=false;
form1.button31.Visible:=false;
form1.button32.Visible:=false;
form1.button24.Visible:=false;

form1.Edit14.top:=131;
form1.Edit15.top:=245;
form1.Edit16.top:=358;
form1.Edit17.top:=473;

form1.Button30.top:=112;
form1.Button31.top:=224;
form1.Button32.top:=338;
form1.Button24.top:=452;

drawaxes; showstat;

form1.Edit14.Visible:=true;
form1.Edit15.Visible:=true;
form1.Edit16.Visible:=true;
form1.Edit17.Visible:=true;

form1.button30.Visible:=True;
form1.button31.Visible:=True;
form1.button32.Visible:=True;
form1.button24.Visible:=True;
(*
form1.button30.enabled:=false;
form1.button31.enabled:=false;
form1.button32.enabled:=false;
form1.button24.enabled:=false;
form1.button7.enabled:=false;
*)
s:='.../model/'+form1.Edit49.Text;

form1.Caption:='Please see results for validation set in file ' + s+ '; Now you can study plots "expr vs calc"';

//form1.label27.Visible:=true; kfkrTotal(valid,DCW,PA,types); // January 24, 2020

(*
//r:=messageDlg('Exit',mtConfirmation,[mbYes,mbNo,mbCancel],0);
r:=messageDlg('Exit',mtConfirmation,[mbYes],0);
//if r=mrNO then CASdelta:=-CASdelta;
if (r=mrYES) then Halt;

assignfile(f,'#test.txt');
rewrite(f);
for k:=1 to nsms do writeln(f,types[k],cas[k],' ',sms[k],dcw[k]:9:3,pa[k]:9:3);
closefile(f);
showmessage('See #test.txt');
*)

// dRsms; // 2019

//kfkrTotal('a',DCW,PA,types); // all compounds

closefile(domain);
closefile(domaino);

end;  // doing of model for the validation set from file "input#.txt"


procedure TForm1.Button1Click(Sender: TObject);
begin
//ActionOfButton28;

//savescreen;
Form1.Label16.visible:=True;
SAS:=True;


end; // stop and save  Oct27 2017

(*
procedure typedata;
var f:text;
    k:integer;
    c0,c1:real;
begin

c0:=StrToFloat(form1.Edit4.Text);
c1:=strToFloat(form1.Edit5.Text);

for k:=1 to nsms do
begin
PAcalc[k]:=c0+c1*dcw[k];
end; // k

assign(f,'pa.txt'); rewrite(f);

for k:=1 to nsms do writeln(f,pa[k]:9:3,pa01[k]:9:3,pacalc[k]:9:3,dcw[k]:9:3);

close(f);
end; //typedata
*)

procedure TForm1.Button29Click(Sender: TObject);

var f:textfile;
    k,j:integer;
    fl,
    s:string;
    c:char;
    r:integer; // to messageDLG: do you want continue optimization?
    c0,c1:real;
begin

show_optimiz := not show_optimiz;

for k:=1 to 1000 do CWactive[k]:=True;

if show_optimiz then
                   begin
                     form1.Button21.Caption:='Show optimization';
                     form1.Edit14.Text:='...';
                     form1.Edit15.Text:='...';
                     form1.Edit16.Text:='...';
                     end
                else form1.Button21.Caption:='Hide';


form1.Button74.Visible:=False;
form1.Edit42.Visible:=False;
form1.Edit54.Visible:=False; // October15,2024 do not show percentage of
                             // shifting for Las Vegas if selected build up model
RedGreen:=False; //May11,2023

loadmethod;

//form1.Button21.Enabled:=False;
form1.Button73.Enabled:=False;

form1.Button20.Visible:=True;
form1.Edit51.Visible:=true;
form1.Edit52.Visible:=true;

//setscreen;

//form1.label27.Visible:=True;

//kfkrtotal(valid,dcw,pa,types);   // january 24, 2020

form1.Button1.Enabled:=False;
form1.Button7.visible:=True;
form1.Button9.visible:=True;
form1.Button73.visible:=True;

form1.Button6.Enabled:=False;
form1.Button15.Enabled:=False;

IniCWs:=False;
Model_is_loaded:=True;

// show_TPTNFPFN:=False;

form1.Button14.Enabled:=false; // phase 1 search for preferable T and N blocked
form1.Button10.Enabled:=false; // phase 2 build up model is blocked

form1.Caption:='CORAL: Calculation of model for external substances';

// loadmethod;

form1.Button16.Visible:=False;
form1.Button17.Visible:=False;
form1.Edit19.Visible:=False;

probe:=1;
dir:='model/';

//Fl:='model/opter';
//readdata(fl);

fl:= 'model/'+form1.Edit50.text; //+'.txt';
//                                      // Oct 6, 2016
//form1.Button5.Visible:=True;          // making of copy for a model
//form1.Edit7.Visible:=True;            // the case of randomization for Apilak

assignfile(f,fl);
{$I-}
reset(f);
{$I+}
if IOResult <> 0 then
begin
showmessage('File '+fl+' is not found');
halt;
end;  // IOresult <>0

form1.Label9.visible:=true;
form1.Label10.visible:=true;
form1.Label38.visible:=true;
form1.Label39.visible:=true;
form1.Label40.visible:=true;
//form1.Label41.visible:=true;

form1.Edit4.Visible:=true;
form1.Edit5.Visible:=true;
form1.Edit44.Visible:=true;
form1.Button33.Visible:=True;
form1.Edit45.Visible:=true;
form1.Edit46.Visible:=true;
form1.Edit47.Visible:=true;
form1.Edit48.Visible:=true;
form1.Edit49.Visible:=true;

form1.Button12.Visible:=true;
form1.Button27.Visible:=true;


readln(f,s); form1.edit1.text:=s;

loadSMILES(form1.Edit1.Text);

readln(f,s); form1.edit9.text:=s;     // N*
readln(f,s); form1.edit39.text:=s;     // T*
// GRAPH boxes
readln(f,c); if c='Y' then form1.checkbox32.Checked:=true else form1.CheckBox32.checked:=false;  // graph
readln(f,c); if c='Y' then form1.checkbox30.Checked:=true else form1.CheckBox30.checked:=false;  // hsg
readln(f,c); if c='Y' then form1.checkbox29.Checked:=true else form1.CheckBox29.checked:=false;  // hfg
readln(f,c); if c='Y' then form1.checkbox31.Checked:=true else form1.CheckBox31.checked:=false;  // gao
readln(f,c); if c='Y' then form1.checkbox9.Checked:=true else form1.CheckBox9.checked:=false;    // ec0
readln(f,c); if c='Y' then form1.checkbox28.Checked:=true else form1.CheckBox28.checked:=false;  // ec1
readln(f,c); if c='Y' then form1.checkbox18.Checked:=true else form1.CheckBox18.checked:=false;  // ec2
readln(f,c); if c='Y' then form1.checkbox10.Checked:=true else form1.CheckBox10.checked:=false;  // ec3

readln(f,c); if c='Y' then form1.checkbox6.Checked:=true else form1.CheckBox6.checked:=false; // pt2
readln(f,c); if c='Y' then form1.checkbox12.Checked:=true else form1.CheckBox12.checked:=false; // pt3
readln(f,c); if c='Y' then form1.checkbox13.Checked:=true else form1.CheckBox13.checked:=false; // vs2
readln(f,c); if c='Y' then form1.checkbox20.Checked:=true else form1.CheckBox20.checked:=false; // nnc
readln(f,c); if c='Y' then form1.checkbox5.Checked:=true else form1.CheckBox5.checked:=false; // c3
readln(f,c); if c='Y' then form1.checkbox8.Checked:=true else form1.CheckBox8.checked:=false; // c4
readln(f,c); if c='Y' then form1.checkbox16.Checked:=true else form1.CheckBox16.checked:=false; // c5
readln(f,c); if c='Y' then form1.checkbox19.Checked:=true else form1.CheckBox19.checked:=false;  // c6
readln(f,c); if c='Y' then form1.checkbox4.Checked:=true else form1.CheckBox4.checked:=false;  // c7

// SMILES boxes
readln(f,c); if c='Y' then form1.checkbox21.Checked:=true else form1.CheckBox21.checked:=false;
readln(f,c); if c='Y' then form1.checkbox22.Checked:=true else form1.CheckBox22.checked:=false;
readln(f,c); if c='Y' then form1.checkbox23.Checked:=true else form1.CheckBox23.checked:=false;
readln(f,c); if c='Y' then form1.checkbox25.Checked:=true else form1.CheckBox25.checked:=false;
readln(f,c); if c='Y' then form1.checkbox27.Checked:=true else form1.CheckBox27.checked:=false;
readln(f,c); if c='Y' then form1.checkbox11.Checked:=true else form1.CheckBox11.checked:=false;
readln(f,c); if c='Y' then form1.checkbox1.Checked:=true else form1.CheckBox1.checked:=false;
readln(f,c); if c='Y' then form1.checkbox2.Checked:=true else form1.CheckBox2.checked:=false;
readln(f,c); if c='Y' then form1.checkbox3.Checked:=true else form1.CheckBox3.checked:=false;

readln(f,c); if c='Y' then form1.RadioButton1.Checked:=true else form1.RadioButton1.Checked:=false;

readln(f,c); if c='Y' then form1.RadioButton2.Checked:=true else form1.RadioButton2.Checked:=false;
readln(f,c); if c='Y' then form1.checkbox24.Checked:=true else form1.CheckBox24.checked:=false;

readln(f,s);form1.edit20.text:=s;
readln(f,s);form1.edit21.text:=s;
readln(f,s);form1.edit22.text:=s;
readln(f,s);form1.edit23.text:=s;
readln(f,s);form1.edit24.text:=s;

readln(f,s);form1.edit42.text:=s;
readln(f,s);form1.edit43.text:=s;


readln(f,s);form1.edit45.text:=s;
readln(f,s);form1.edit46.text:=s;

// October 6, 2021
readln(f,c0); form1.Edit4.Text:=FloatToStrF(c0, FFfixed, 12,7);
readln(f,c1); form1.Edit5.Text:=FloatToStrF(c1, FFfixed, 12,7);

//readln(f,s);form1.edit4.text:=s;
//readln(f,s);form1.edit5.text:=s;

readln(f,n_glb);
for k:=1 to n_glb do
begin
for j:=1 to MaxCharSF do
read(f,global_SF_list[k][j]);
readln(f,cw[1,k],CWdefect[k]);
end;

readln(f,s); form1.Edit39.Text:=s;      // Threshold
form1.Label39.Caption:='DCW('+form1.edit39.text+','+form1.edit9.text+')=';

readln(f,nsms);
for k:=1 to nsms do
begin
read(f,nuc[k,0]);
for j:=1 to nuc[k,0] do read(f,nuc[k,j]);
readln(f);
end; // k

Readln(f,AveDefectSMILES);

//oct25 2017
for k:=1 to n_glb do
Readln(f,TRNs[k],CLBs[k],TSTs[k],TRN[k],CLB[k],TST[k]);
Readln(f,SMILESAk);
Readln(f,s);        form1.Edit39.Text:=s;

Readln(f,s);  form1.edit36.text:=s; // W%
Readln(f,s);  form1.edit13.text:=s; // III
Readln(f,s);  form1.edit12.text:=s; // IIO
Readln(f,s);  form1.edit8.text:=s;  // IOI
Readln(f,s);  form1.edit32.text:=s; // IOO
Readln(f,s);  form1.edit33.text:=s; // ALL
Readln(f,s);  form1.edit35.text:=s; // SplitDefect
Readln(f,s);  form1.edit2.text:=s;  // NormSplitDefect

closefile(f);

//  June 23, 2011 Output of correlations graphically

dodcw;
showstat;

//typedata; // December14,2020

c0:=StrToFloat(form1.Edit4.Text);
c1:=strToFloat(form1.Edit5.Text);

for k:=1 to nsms do
begin
PAcalc[k]:=c0+c1*dcw[k];
end; // k



drawaxes;

level1:=True; level2:=True; level3:=True;

if not Form1.checkBox1.checked then begin level1:=False; end;
if not Form1.checkBox2.checked then begin level2:=False; end;
if not Form1.checkBox3.checked then begin level3:=False; end;

form1.Button30.Enabled:=true;
form1.Button31.Enabled:=true;
form1.Button32.Enabled:=true;
form1.Button7.Enabled:=true;
form1.Button9.Enabled:=True;
//form1.Button73.Enabled:=True;

// oct25 2017

//saveCWs('before.txt');

if Model_is_loaded then
begin
//r:=messageDlg('Continue optimization?',mtConfirmation,[mbYes,mbNo],0);
//if r=mrYes then
     begin
     form1.Button8.Visible:=true;

//     kfkrtotal(valid,dcw,pa,types);   // january 24, 2020

//     ActionOfButton10;
//     ActionOfButton11;
     end; // mrYes
end; // model is loaded

//kfkrtotal(valid,dcw,pa,types);   // january 24, 2020

end;

procedure TForm1.Button30Click(Sender: TObject);
begin
GraphParol:=Train;
//showmessage(GraphParol+' is selected');
end;

procedure TForm1.Button31Click(Sender: TObject);
begin
GraphParol:=Calib;
if form1.Edit15.Text='Set is empty' then
begin
showmessage('This set is empty. Analysis is nonsence')
end; // set is empty
//showmessage(GraphParol+' is selected');
end;

procedure TForm1.Button32Click(Sender: TObject);
begin
GraphParol:=Test;
//showmessage(GraphParol+' is selected');
end;

procedure TForm1.Button24Click(Sender: TObject);
begin
GraphParol:=Valid;
//showmessage(GraphParol+' is selected');
end;

procedure TForm1.Button33Click(Sender: TObject);
begin
form1.Edit44.Text:='';
end;


procedure TForm1.Button34Click(Sender: TObject);
begin
dobutton(34);
end;

procedure TForm1.Button35Click(Sender: TObject);
begin
dobutton(35);
end;

procedure TForm1.Button36Click(Sender: TObject);
begin
dobutton(36);
end;

procedure TForm1.Button37Click(Sender: TObject);
begin
dobutton(37);
end;

procedure TForm1.Button38Click(Sender: TObject);
begin
dobutton(38);
end;

procedure TForm1.Button39Click(Sender: TObject);
begin
dobutton(39);
end;

procedure TForm1.Button40Click(Sender: TObject);
begin
dobutton(40);
end;

procedure TForm1.Button41Click(Sender: TObject);
begin
dobutton(41);
end;

procedure TForm1.Button42Click(Sender: TObject);
begin
dobutton(42);
end;

procedure TForm1.Button43Click(Sender: TObject);
begin
dobutton(43);
end;

procedure TForm1.Button44Click(Sender: TObject);
begin
dobutton(44);
end;

procedure TForm1.Button45Click(Sender: TObject);
begin
dobutton(45);
end;

procedure TForm1.Button46Click(Sender: TObject);
begin
dobutton(46);
end;

procedure TForm1.Button47Click(Sender: TObject);
begin
dobutton(47);
end;

procedure TForm1.Button48Click(Sender: TObject);
begin
dobutton(48);
end;

procedure TForm1.Button49Click(Sender: TObject);
begin
dobutton(49);
end;

procedure TForm1.Button55Click(Sender: TObject);
begin
dobutton(55);
end;

procedure TForm1.Button56Click(Sender: TObject);
begin
dobutton(56);
end;

procedure TForm1.Button57Click(Sender: TObject);
begin
dobutton(57);
end;

procedure TForm1.Button58Click(Sender: TObject);
begin
dobutton(58);
end;

procedure TForm1.Button59Click(Sender: TObject);
begin
dobutton(59);
end;

procedure TForm1.Button50Click(Sender: TObject);
begin
dobutton(50);
end;

procedure TForm1.Button60Click(Sender: TObject);
begin
dobutton(60);
end;

procedure TForm1.Button61Click(Sender: TObject);
begin
dobutton(61);
end;

procedure TForm1.Button62Click(Sender: TObject);
begin
dobutton(62);
end;

procedure TForm1.Button63Click(Sender: TObject);
begin
dobutton(63);
end;

procedure TForm1.Button51Click(Sender: TObject);
begin
dobutton(51);
end;

procedure TForm1.Button64Click(Sender: TObject);
begin
dobutton(64);
end;

procedure TForm1.Button65Click(Sender: TObject);
begin
dobutton(65);
end;

procedure TForm1.Button66Click(Sender: TObject);
begin
dobutton(66);
end;

procedure TForm1.Button52Click(Sender: TObject);
begin
dobutton(52);
end;

procedure TForm1.Button67Click(Sender: TObject);
begin
dobutton(67);
end;

procedure TForm1.Button68Click(Sender: TObject);
begin
dobutton(68);
end;

procedure TForm1.Button53Click(Sender: TObject);
begin
dobutton(53);
end;

procedure TForm1.Button69Click(Sender: TObject);
begin
dobutton(69);
end;

procedure TForm1.Button54Click(Sender: TObject);
begin
dobutton(54);
end;

procedure do_all;
var k:integer;
begin
for k:=34 to 69 do dobutton(k);
end;

procedure TForm1.Button70Click(Sender: TObject);
begin
do_all
end;

procedure TForm1.Button71Click(Sender: TObject);
begin
dobutton(71);
end;

procedure TForm1.Button72Click(Sender: TObject);
begin
dobutton(72);
end;

procedure TForm1.Button73Click(Sender: TObject);
begin
dotsize:=dotsize+1;
if not (DotSize in [0,1,2]) then dotsize:=0;
form1.Button73.Caption:='DotSize-'+IntToStr(dotsize);
end;

procedure TForm1.Button74Click(Sender: TObject);
var r:integer;
begin

LV:=-1; // May27,2024
LVbest:=0; //September30,2024
LVRCmax:=0.0;

form1.Edit42.Visible:=True;
form1.Edit54.Visible:=True;

form1.Edit24.Text:=form1.Edit42.Text; // May13,2024
form1.Edit42.Top:=235;
form1.Edit54.Top:=235;  // October15,2024 percentage of shifting in Las Vegas
                        // algorithm
savemethod;

form1.Button10.Visible:=False;

LoadMethod;
version:=5;
R2Cmax:=0.0;
Form1.Edit1.Text:='#TotalSet'+Chr(39)+'.txt';

APCV:=TRUE; // October1,2024 Let start from APCV shifting, not from APC
//r:=messageDLG('Is the modification of validation set possible?',mtConfirmation,[mbYes,mbNo,mbCancel],0);
//if r=mrNO then APCV:=FALSE;

loadSMILES(Form1.Edit1.Text); // taken TotalSet'.txt
saveSplit; // save model/#TotalSet.txt

form1.Edit24.Text:=Form1.Edit42.Text;

form1.Edit23.Text:=Form1.Edit22.Text;

// percentexchanges:=0.1;  Oct0ber11,2024 user select the value via edit54.text

//r:=messageDlg('APC Las Vegas [y]?',mtConfirmation,[mbYes,mbNo],0);
//if r=mrNO then APCV:=true else APCV:=False;

//APCV:=TRUE; // only A, P, and C sets will be shifting April17,2024

form1.Button1.Visible:=False; // save current CWs is impossible
form1.Button74.Visible:=False;
form1.Button14.Left:=272;
form1.Button14.Top:=232;
form1.Button14.width:=257;
form1.Button14.Font.Size:=9;
form1.button14.Caption:='Start Las Vegas Calculations';
form1.Edit24.Text:=form1.Edit42.Text; // May13,2024

form1.Button13.Left:=272;
form1.Button13.Top:=242;
form1.Button13.width:=257;
form1.Button13.Font.Size:=9;
form1.Button13.Height:=22;
// form1.Button13.Visible:=True;   November3,2024

//APCV := not APCV;
if apcv then button13.Caption:='APCV style'
        else button13.Caption:='APC style';

savemethod;

//form1.Edit22.Text:=Form1.Edit23.Text; // block phase1 like work April17,2024



end;

procedure TForm1.Button75Click(Sender: TObject);
begin
dobutton(75);
end;

end.

